我有一个很长的问题。我想在 Python 中将它分成几行。在 JavaScript 中执行此操作的一种方法是使用多个句子并使用 +
运算符将它们连接起来(我知道,这可能不是最有效的方法,但我并不真正关心性能在这个阶段,只是代码可读性)。示例:
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
我尝试在 Python 中做类似的事情,但没有成功,所以我使用 \
来拆分长字符串。但是,我不确定这是否是唯一/最好/pythonicest 的方法。看起来很尴尬。
实际代码:
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 ...'
不需要逗号,只需将要连接在一起的字符串放在一对括号中,并确保考虑到任何需要的空格和换行符。
关于python - 如何将长字符串的定义拆分为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660435/