我有一个很长的疑问。我想用Python将它分成几行。在JavaScript中实现这一点的一种方法是使用几个句子并用+运算符将它们连接起来(我知道,也许这不是最有效的方法,但我并不真正关心这个阶段的性能,只是代码的可读性)。例子:
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
我尝试在Python中做类似的事情,但没有成功,所以我使用了\来拆分长字符串。然而,我不确定这是否是唯一/最好/最蟒蛇的做法。看起来很尴尬。实际代码:
query = 'SELECT action.descr as "action", '\
'role.id as role_id,'\
'role.descr as role'\
'FROM '\
'public.role_action_def,'\
'public.role,'\
'public.record_def, '\
'public.action'\
'WHERE role.id = role_action_def.role_id AND'\
'record_def.id = role_action_def.def_id AND'\
'action.id = role_action_def.action_id AND'\
'role_action_def.account_id = ' + account_id + ' AND'\
'record_def.account_id=' + account_id + ' AND'\
'def_id=' + def_id
“la”Scala方式(但我认为这是OP要求的最具Python风格的方式):
description = """
| The intention of this module is to provide a method to
| pass meta information in markdown_ header files for
| using it in jinja_ templates.
|
| Also, to provide a method to use markdown files as jinja
| templates. Maybe you prefer to see the code than
| to install it.""".replace('\n | \n','\n').replace(' | ',' ')
如果您希望最后的str没有跳转行,只需将\n放在第二个替换的第一个参数的开头:
.replace('\n | ',' ')`.
注意:“…templates.”和“另外,…”之间的白线需要在|后面加一个空格。
我喜欢这种方法,因为它有阅读的特权。在我们有长串的情况下,没有办法!根据您所处的缩进级别,每行仍限于80个字符。。。好没必要说别的
在我看来,Python风格指南仍然非常模糊。我采用了埃罗·奥尔顿的方法,因为它有利于阅读和常识。我明白,风格指南应该帮助我们,而不是让我们的生活一团糟。
class ClassName():
def method_name():
if condition_0:
if condition_1:
if condition_2:
some_variable_0 =\
"""
some_js_func_call(
undefined,
{
'some_attr_0': 'value_0',
'some_attr_1': 'value_1',
'some_attr_2': '""" + some_variable_1 + """'
},
undefined,
undefined,
true
)
"""
我发现,当构建长字符串时,您通常会做一些类似于构建SQL查询的事情,在这种情况下,这是最好的:
query = ' '.join(( # Note double parentheses. join() takes an iterable
"SELECT foo",
"FROM bar",
"WHERE baz",
))
Levon的建议很好,但可能容易出错:
query = (
"SELECT foo"
"FROM bar"
"WHERE baz"
)
query == "SELECT fooFROM barWHERE baz" # Probably not what you want
我个人认为,以下是用Python编写原始SQL查询的最佳(简单、安全和Python化)方法,尤其是在使用Python的sqlite3模块时:
query = '''
SELECT
action.descr as action,
role.id as role_id,
role.descr as role
FROM
public.role_action_def,
public.role,
public.record_def,
public.action
WHERE
role.id = role_action_def.role_id
AND record_def.id = role_action_def.def_id
AND action.id = role_action_def.action_id
AND role_action_def.account_id = ?
AND record_def.account_id = ?
AND def_id = ?
'''
vars = (account_id, account_id, def_id) # a tuple of query variables
cursor.execute(query, vars) # using Python's sqlite3 module
Pros
整洁而简单的代码(Pythonic!)避免SQL注入与Python 2和Python 3兼容(毕竟是Pythonic)不需要字符串串联无需确保每行最右边的字符是空格
Cons
由于查询中的变量被替换为?占位符,它可能会变得有点难以跟踪哪个?当查询中有很多Python变量时,将由哪个Python变量替换。