Python 3.6中的f-strings不支持以下语法?如果我连接我的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)
返回:
This longer message is intended to contain the sub-message here: {SUB_MSG}
如果我删除了行连接:
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)
它按预期工作:
This longer message is intended to contain the sub-message here: This is the original message.
在PEP 498中,明确不支持f / string中的反斜杠:
转义序列
反斜杠可能不会出现在表达式部分中 f-strings,所以你不能使用它们,例如,逃避引号 在f-strings里面:
>>> f'{\'quoted string\'}'
在f字符串的表达部分中考虑了行连接'因此不受支持?
答案 0 :(得分:6)
您必须将两个字符串标记为f
- 字符串才能使其正常工作,否则第二个字符串将被解释为普通字符串:
SUB_MSG = "This is the original message."
MAIN_MSG = f"test " \
f"{SUB_MSG}"
print(MAIN_MSG)
嗯,在这种情况下,您也可以将第二个字符串设为f字符串,因为第一个字符串不包含要插入的内容:
MAIN_MSG = "test " \
f"{SUB_MSG}"
请注意,这会影响所有字符串前缀,而不仅仅是f-strings:
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
答案 1 :(得分:2)
试试这个(注意延续线上的额外“f”):
SUB_MSG = "This is the original message."
MAIN_MSG = f"This longer message is intended to contain " \
f"the sub-message here: {SUB_MSG}"
print(MAIN_MSG)