我有一个非常长的查询。我想在Python中把它分成几行。在JavaScript中的一个方法是使用几个句子,用+
运算符连接它们(我知道,也许这不是最有效的方法,但在这个阶段我并不关心性能,只关心代码的可读性)。例子。
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
我试着在Python中做类似的事情,但没有成功,所以我用`{13426759}来分割长字符串。然而,我不确定这是否是唯一/最好/最原始的方法。它看起来很笨拙。 实际代码。
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 ..."
)
这将***不包括任何额外的空白或换行(这是一个特意的例子,显示了跳过空白的效果)。
不需要逗号,只需将要连接的字符串放在一对小括号中,并确保考虑到任何需要的空白和换行。
如果你不想要多行字符串,而只是有一个长的单行字符串,你可以使用圆括号,只要确保你在字符串段之间不包括逗号,那么它将是一个元组。
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)
在像你构建的SQL语句中,多行字符串也是可以的。 但是,如果多行字符串所包含的额外空白会成为一个问题,那么这将是实现你所希望的一个好方法。