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

当前回答

PEP 8风格指南建议使用括号:

包装长行的首选方式是在括号、括号和大括号内使用Python的隐含行延续。通过将表达式括在括号中,可以在多行上打断长行。应优先使用这些字符,而不是使用反斜杠作为换行符。

例子:

long_string = (
    "This is a lengthy string that takes up a lot of space. I am going to "
    "keep on typing words to fill up more and more space to show how you can "
    "split the string across multiple lines."
)

其他回答

我个人认为,以下是用Python编写原始SQL查询的最佳(简单、安全和Python化)方法,尤其是在使用Python的sqlite3模块时:

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 = ?
        AND record_def.account_id = ?
        AND def_id = ?
'''
vars = (account_id, account_id, def_id)   # a tuple of query variables
cursor.execute(query, vars)   # using Python's sqlite3 module

Pros

整洁而简单的代码(Pythonic!)避免SQL注入与Python 2和Python 3兼容(毕竟是Pythonic)不需要字符串串联无需确保每行最右边的字符是空格

Cons

由于查询中的变量被替换为?占位符,它可能会变得有点难以跟踪哪个?当查询中有很多Python变量时,将由哪个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)

在您正在构建的SQL语句中,多行字符串也可以。但是,如果多行字符串包含的额外空白是一个问题,那么这将是一个实现您所需功能的好方法。

如注释中所述,以这种方式连接SQL查询是SQL注入安全风险,因此请使用数据库的参数化查询功能来防止这种情况发生。然而,我保留了答案,因为它直接回答了问题。

tl;dr:使用“”和“”来换行字符串,如中所示

string = """\
This is a long string
spanning multiple lines.
"""

从Python官方文档中:

字符串文本可以跨越多行。一种方法是使用三引号:“”“…”“”或“”“”…“”。行的结束是自动的包含在字符串中,但可以通过添加\在线路的末端。以下示例:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

生成以下输出(注意,初始换行符不是包括在内):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

我知道这是一个相当古老的问题,但Python在此期间发生了变化,我看不到这个答案,所以我们开始。

另一种方法是使用\剪切当前行并移动到另一行:

print("This line will \
get carried over to\
 the new line.\
Notice how this\
word will be together because \
of no space around it")

其他人已经提到了圆括号方法,但我想补充一点,使用圆括号时,允许内联注释。

对每个片段的注释:

nursery_rhyme = (
    'Mary had a little lamb,'          # Comments are great!
    'its fleece was white as snow.'
    'And everywhere that Mary went,'
    'her sheep would surely go.'       # What a pesky sheep.
)

继续后不允许注释:

使用反斜杠行延续符(\)时,不允许使用注释。您将收到一个SyntaxError:一行接一行的连续字符错误。

nursery_rhyme = 'Mary had a little lamb,' \  # These comments
    'its fleece was white as snow.'       \  # are invalid!
    'And everywhere that Mary went,'      \
    'her sheep would surely go.'
# => SyntaxError: unexpected character after line continuation character

Regex字符串的更好注释:

基于以下示例https://docs.python.org/3/library/re.html#re.VERBOSE,

a = re.compile(
    r'\d+'  # the integral part
    r'\.'   # the decimal point
    r'\d*'  # some fractional digits
)
# Using VERBOSE flag, IDE usually can't syntax highight the string comment.
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)