我有一个很长的疑问。我想用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

当前回答

添加@Levon的答案。。。。

1.创建如下多行字符串:

paragraph = """this is a very
        long string if I had the
        energy to type more and more ..."""

print(paragraph)

输出:

'this is a very\n        long string if I had the\n        energy to type more and more ...'

此字符串将包含换行符和空格。因此,请移除它们。

2.使用正则表达式删除多余的空格

paragraph = re.sub('\s+', ' ', paragraph)
print(paragraph)

输出:

'this is a very long string if I had the energy to type more and more ...'

其他回答

如果不需要多行字符串,而只需要一个长的单行字符串,则可以使用括号。只需确保字符串段之间不包含逗号(那么它将是一个元组)。

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注入安全风险,因此请使用数据库的参数化查询功能来防止这种情况发生。然而,我保留了答案,因为它直接回答了问题。

我使用递归函数来构建复杂的SQL查询。此技术通常可用于构建大型字符串,同时保持代码可读性。

# Utility function to recursively resolve SQL statements.
# CAUTION: Use this function carefully, Pass correct SQL parameters {},
# TODO: This should never happen but check for infinite loops
def resolveSQL(sql_seed, sqlparams):
    sql = sql_seed % (sqlparams)
    if sql == sql_seed:
        return ' '.join([x.strip() for x in sql.split()])
    else:
        return resolveSQL(sql, sqlparams)

P.S.:看看很棒的python-sqlparse库,如果需要,可以打印SQL查询。

为了在字典内定义长字符串,保留换行符但省略空格,我最终以如下常量定义字符串:

LONG_STRING = \
"""
This is a long sting
that contains newlines.
The newlines are important.
"""

my_dict = {
   'foo': 'bar',
   'string': LONG_STRING
}

“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.”和“另外,…”之间的白线需要在|后面加一个空格。

在Python>=3.6中,可以使用格式化字符串文本(f字符串)

query= f'''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}'''