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

问题描述 投票:0回答:4

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

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

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

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

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

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

python string formatting escaping string-formatting
4个回答
20
投票

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

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

10
投票

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

\
:

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 的答案 有效,但前提是字符串中没有混合使用

'''
"""
三引号。用反斜杠always转义引号字符是可行的。

烦恼#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
投票

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

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

0
投票

对于你不知道的情况,今天你可以只加前缀

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]}
\"\"\"
"""
© www.soinside.com 2019 - 2024. All rights reserved.