反斜杠和三引号之间有区别吗?

Is there a difference between backslash and triple quotes?

我知道对于超过 1 行的字符串赋值,您可以使用反斜杠、括号或三重引号。有什么实际区别吗?哪个被认为是更好的编码实践?

例如:

STR1 = """Peanut
        butter
        jam"""

STR2 = "Peanut" \
       "butter" \
       "jam"

STR3 = ("Peanut"
        "butter"
        "jam")

所有这些 运行 都很好,但哪个更不容易出现未来的错误,或者是更好的做法?

确实存在差异,因为使用三引号不会减少换行,\n,当按 Enter 时,其他的不包括它们,只有引号内的内容是使用过。

看看这个打印每个的简单代码:

STR1 = """Peanut
        butter
        jam"""

STR2 = "Peanut" \
       "butter" \
       "jam"

STR3 = ("Peanut"
        "butter"
        "jam")


print(STR1)
print(STR2)
print(STR3)

结果如下:

Peanut
        butter
        jam
Peanutbutterjam
Peanutbutterjam

STR1 正如所指出的 , actually a different string to STR2 and STR3. This may not be relevant, depending on the case (e.g. when using regular expressions you can turn on the verbose flag 忽略多余的空格)。

STR2STR3之间,guidance in PEP8表示后者:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

有了反斜杠,你也不能发表评论:

>>> STR2 = "Peanut" \
...        "butter" \  # optional
  File "<stdin>", line 2
    "butter" \  # optional
                         ^
SyntaxError: unexpected character after line continuation character
>>> STR3 = ("Peanut"
...         "butter"  # optional
...         "jam")
>>>