【发布时间】:2017-10-24 22:05:05
【问题描述】:
Python 3.6 中的 f-strings 是否不支持以下语法?如果我加入我的 f 字符串,则不会发生替换:
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 字符串中:
转义序列
反斜杠不能出现在 f 字符串,因此您不能使用它们,例如,转义引号 在 f 字符串中:
>>> f'{\'quoted string\'}'
是否将行连接视为“在 f 字符串的表达式部分内”并因此不受支持?
【问题讨论】:
-
在 f-strings 的表达式部分 中不支持,其他地方也不支持。此外,只需将
f添加到第二个字符串文字。这与其他字符串前缀的工作方式一致:len(r"\\" "\\") == 3.
标签: python string python-3.x python-3.6 f-string