我有一个很长的疑问。我想用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
通常,我对多行注释/string使用list和join。
lines = list()
lines.append('SELECT action.enter code here descr as "action", ')
lines.append('role.id as role_id,')
lines.append('role.descr as role')
lines.append('FROM ')
lines.append('public.role_action_def,')
lines.append('public.role,')
lines.append('public.record_def, ')
lines.append('public.action')
query = " ".join(lines)
您可以使用任何字符串连接所有这些列表元素,如“\n”(换行符)或“,”(逗号)或“”(空格)。
我发现,当构建长字符串时,您通常会做一些类似于构建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
“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.”和“另外,…”之间的白线需要在|后面加一个空格。
你说的是多行字符串吗?简单,使用三引号开始和结束它们。
s = """ this is a very
long string if I had the
energy to type more and more ..."""
您也可以使用单引号(当然,在开始和结束处有3个引号),并像对待任何其他字符串一样对待生成的字符串。
注意:与任何字符串一样,起始引号和结束引号之间的任何内容都将成为字符串的一部分,因此本示例有一个前导空格(如@root45所指出的)。此字符串还将包含空格和换行符。
即。,:
' this is a very\n long string if I had the\n energy to type more and more ...'
最后,您还可以在Python中构造如下的长行:
s = ("this is a very"
"long string too"
"for sure ..."
)
这将不包括任何额外的空格或换行符(这是一个故意的示例,显示跳过空格的效果):
'this is a verylong string toofor sure ...'
不需要逗号,只需将要连接在一起的字符串放入一对括号中,并确保考虑到任何需要的空格和换行符。
例如:
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1={} "
"and condition2={}").format(1, 2)
Output: 'select field1, field2, field3, field4 from table
where condition1=1 and condition2=2'
如果条件的值应该是字符串,可以这样做:
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1='{0}' "
"and condition2='{1}'").format('2016-10-12', '2017-10-12')
Output: "select field1, field2, field3, field4 from table where
condition1='2016-10-12' and condition2='2017-10-12'"