如何使用 Python 格式化内部带有三重引号的多行字符串?

How to format a multi line string with triple quotes inside using Python?

我在网上找不到这个,但基本上我有这样一个字符串:

s = "name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
"

我需要像这样使用变量来格式化这个字符串:

s.format("alice", "N/A", "alice", 18, "missing person")

我无法更改那里的三重引号,因为将使用我的字符串的程序需要这样做,否则将无法工作。

我怎样才能正确地得到这个字符串 declared/escaped?

您可以对字符串使用三重单引号:

s = '''name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
'''

print s.format("alice", "N/A", "alice", 18, "missing person")

输出:

name=alice,
address=N/A,
nickname=alice,
age=18,
comments=
"""
missing person
"""

您可以使用@niemmi 的方法,效果非常好。您还可以在每行的末尾添加一个反斜杠,以表示您将在下一行继续:

s = 'name={0},\
address={1},\
nickname={2},\
age={3},\
comments=\
"""\
{4}\
"""\
'

您可以像转义任何其他引号字符一样转义字符串中的三引号,使用 \:

s = """name={0},
address={1},
nickname={2},
age={3},
comments=
\"\"\"
{4}
\"\"\"
"""

严格来说,你只需要转义一个"字符---足以防止出现三重"""---但我发现转义所有三个让我的意图更加明确。

稍后...

sf = s.format("alice", "N/A", "alice", 18, "missing person")
print(sf)
print('----')
print(repr(sf))

...产生:

name=alice,
address=N/A,
nickname=alice,
age=18,
comments=
"""
missing person
"""

----
'name=alice,\naddress=N/A,\nnickname=alice,\nage=18,\ncomments=\n"""\nmissing person\n"""\n'

niemmi's answer 有效,但前提是字符串中没有混合使用 '''""" 三重引号。用反斜杠转义引号字符 总是 有效。

烦恼 #1:尾随换行符

我打印了一行破折号以突出显示 s 保留了最后三个转义引号字符和实际结束字符串的三重引号之间的换行符。要从文字中删除它:

s = """[as before...]
\"\"\"
{4}
\"\"\""""

烦恼 #2:在文字中保留缩进

s 文字的第二行和后续行必须与第一(左侧)列齐平。在缩进块内整齐排列的三引号字符串:

def indents_appear_in_string_literal():
    # This looks good but doesn't work right.
    s = """name={0},
    address={1},
    nickname={2},
    age={3},
    comments=
    \"\"\"
    {4}
    \"\"\"
    """
    sf = s.format("alice", "N/A", "alice", 18, "missing person")
    print(sf)
    print('----')
    print(repr(sf))
    return

...将保留文字内的缩进:

name=alice,
    address=N/A,
    nickname=alice,
    age=18,
    comments=
    """
    missing person
    """

----
'name=alice,\n    address=N/A,\n    nickname=alice,\n    age=18,\n    comments=\n    """\n    missing person\n    """\n    '

只是为了你不知道的情况,今天你可以前缀f""" ... """

所以:

vs = ["alice", "N/A", "alice", 18, "missing person"]
s = f"""name={vs[0]},
address={vs[1]},
nickname={vs[2]},
age={vs[3]},
comments=
\"\"\"
{vs[4]}
\"\"\"
"""