我有一个很长的问题。我想用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
发布于 2012-05-19 06:26:35
如果您不需要多行字符串,但只需要一个很长的单行字符串,则可以使用括号。只需确保字符串段之间不包含逗号(然后它将是一个元组)。
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语句中,多行字符串也可以。但是,如果多行字符串包含的额外空格是一个问题,那么这将是实现您想要的内容的好方法。
正如注释中所指出的,以这种方式连接SQL查询是一种SQL注入,因此使用数据库的参数化查询功能可以防止这种情况发生。但是,我把答案留在原处,因为它直接回答了所提出的问题。
发布于 2014-06-21 00:16:56
\
的断行对我来说很管用。下面是一个示例:
longStr = "This is a very long string " \
"that I wrote to help somebody " \
"who had a question about " \
"writing long strings in Python"
发布于 2013-01-04 18:39:30
我发现我对这个很满意:
string = """This is a
very long string,
containing commas,
that I split up
for readability""".replace('\n',' ')
https://stackoverflow.com/questions/10660435
复制相似问题