线串连接是否不受f字符串支持?

JS.*_*JS. 4 python string python-3.x python-3.6 f-string

Python 3.6中的f字符串不支持以下语法吗?如果我连接我的f-string,则不会发生替换:

SUB_MSG = "This is the original message."

MAIN_MSG = f"This longer message is intended to contain " \
             "the sub-message here: {SUB_MSG}"

print(MAIN_MSG)
Run Code Online (Sandbox Code Playgroud)

收益:

This longer message is intended to contain the sub-message here: {SUB_MSG}
Run Code Online (Sandbox Code Playgroud)

如果我删除了行连接:

SUB_MSG = "This is the original message."

MAIN_MSG = f"This longer message is intended to contain the sub-message here: {SUB_MSG}"

print(MAIN_MSG)
Run Code Online (Sandbox Code Playgroud)

它按预期工作:

This longer message is intended to contain the sub-message here: This is the original message.
Run Code Online (Sandbox Code Playgroud)

PEP 498,反斜杠的F-串并不明确支持:

逃脱序列

反斜杠可能不会出现在f字符串的表达式部分中,因此您不能使用它们,例如,转义f字符串中的引号:

>>> f'{\'quoted string\'}'
Run Code Online (Sandbox Code Playgroud)

线连接是否被认为是"在f字符串的表达式部分内部",因此不受支持?

MSe*_*ert 6

您必须将两个字符串标记为f-strings以使其工作,否则第二个字符串将被解释为普通字符串:

SUB_MSG = "This is the original message."

MAIN_MSG = f"test " \
           f"{SUB_MSG}"

print(MAIN_MSG)
Run Code Online (Sandbox Code Playgroud)

好吧,在这种情况下,您也可以将第二个字符串设为f字符串,因为第一个字符串不包含要插入的内容:

MAIN_MSG = "test " \
           f"{SUB_MSG}"
Run Code Online (Sandbox Code Playgroud)

请注意,这会影响所有字符串前缀,而不仅仅是f字符串:

a = r"\n" \
     "\n"
a   # '\\n\n'   <- only the first one was interpreted as raw string

a = b"\n" \
     "\n"   
# SyntaxError: cannot mix bytes and nonbytes literals
Run Code Online (Sandbox Code Playgroud)