python - f 字符串不支持行连接吗?

标签 python string python-3.x python-3.6 f-string

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 字符串中明确不支持:

Escape sequences

Backslashes may not appear inside the expression portions of f-strings, so you cannot use them, for example, to escape quotes inside f-strings:

>>> f'{\'quoted string\'}'

行连接是否被视为“在 f 字符串的表达式部分内”,因此不受支持?

最佳答案

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

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 字符串:

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

关于python - f 字符串不支持行连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920786/

相关文章:

python - 如何在 Google App Engine Python 的请求处理程序中使用 delete() 方法

c - 在C语言中如何将int转换为字符串?

Javascript交换字符串中的字符

python - Anaconda: cannot import cv2 even though opencv is installed (how to install opencv3 for python3)

python - 为什么 "any()"比使用循环运行得慢?

Python - 通过连接坐标查找正方形的数量

python - 如果给定 python 中的一些元组索引,如何获取子元组列表?

python - pygtk WINDOW_TYPE_HINT_DOCK 不适用于 Windows

c# - 为什么 String 类是最终的?

python - 仅对 pandas 数据框的给定列中的某些行求和