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

当前回答

使用“”符号时,还可以包含变量:

foo = '1234'

long_string = """fosdl a sdlfklaskdf as
as df ajsdfj asdfa sld
a sdf alsdfl alsdfl """ +  foo + """ aks
asdkfkasdk fak"""

更好的方法是使用命名参数和.format():

body = """
<html>
<head>
</head>
<body>
    <p>Lorem ipsum.</p>
    <dl>
        <dt>Asdf:</dt>     <dd><a href="{link}">{name}</a></dd>
    </dl>
    </body>
</html>
""".format(
    link='http://www.asdf.com',
    name='Asdf',
)

print(body)

其他回答

从Python官方文档中:

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

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

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

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

对每个片段的注释:

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)

通常,我对多行注释/string使用list和join。

lines = list()
lines.append('SELECT action.enter code here descr as "action", ')
lines.append('role.id as role_id,')
lines.append('role.descr as role')
lines.append('FROM ')
lines.append('public.role_action_def,')
lines.append('public.role,')
lines.append('public.record_def, ')
lines.append('public.action')
query = " ".join(lines)

您可以使用任何字符串连接所有这些列表元素,如“\n”(换行符)或“,”(逗号)或“”(空格)。

您还可以将SQL语句放置在单独的文件action.SQL中,并使用以下命令将其加载到.py文件中:

with open('action.sql') as f:
   query = f.read()

因此,SQL语句将与Python代码分离。如果SQL语句中有需要从Python填充的参数,则可以使用字符串格式(如%s或{field})。

我认为当代码(例如,变量)缩进并且输出字符串应该是单行(没有换行)时,另一个选项更可读:

def some_method():

    long_string = """
A presumptuous long string
which looks a bit nicer
in a text editor when
written over multiple lines
""".strip('\n').replace('\n', ' ')

    return long_string