我有一个很长的疑问。我想用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
tl;dr:使用“”和“”来换行字符串,如中所示
string = """\
This is a long string
spanning multiple lines.
"""
从Python官方文档中:
字符串文本可以跨越多行。一种方法是使用三引号:“”“…”“”或“”“”…“”。行的结束是自动的包含在字符串中,但可以通过添加\在线路的末端。以下示例:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
生成以下输出(注意,初始换行符不是包括在内):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
我使用递归函数来构建复杂的SQL查询。此技术通常可用于构建大型字符串,同时保持代码可读性。
# Utility function to recursively resolve SQL statements.
# CAUTION: Use this function carefully, Pass correct SQL parameters {},
# TODO: This should never happen but check for infinite loops
def resolveSQL(sql_seed, sqlparams):
sql = sql_seed % (sqlparams)
if sql == sql_seed:
return ' '.join([x.strip() for x in sql.split()])
else:
return resolveSQL(sql, sqlparams)
P.S.:看看很棒的python-sqlparse库,如果需要,可以打印SQL查询。
在Python>=3.6中,可以使用格式化字符串文本(f字符串)
query= f'''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}'''
我发现,当构建长字符串时,您通常会做一些类似于构建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