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

时间:2016-06-17 02:50:22

标签: python string formatting escaping string-formatting

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

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

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

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

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

如何正确声明/转义此字符串?

3 个答案:

答案 0 :(得分:7)

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

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    '

答案 1 :(得分:6)

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

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
"""

答案 2 :(得分:1)

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

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