我有一个很长的查询。我想在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
最佳答案
您在谈论多行字符串吗?容易,使用三引号将其开始和结束。
s = """ this is a very
long string if I had the
energy to type more and more ..."""
您也可以使用单引号(当然在开始和结束时使用3个单引号),并将生成的字符串
s
与其他任何字符串一样对待。注意:与任何字符串一样,引号和结束引号之间的任何内容都将成为字符串的一部分,因此本示例中有一个前导空格(如@ 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 ...'
无需逗号,只需将要连接的字符串放在一对括号中,并确保考虑到任何需要的空格和换行符。