讨论数量:
D:\>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> url = "http:\\python.com"
>>> print(f"{url.removeprefix('http:\\')}")
File "<stdin>", line 1
print(f"{url.removeprefix('http:\\')}")
^
SyntaxError: f-string expression part cannot include a backslash
D:\>python
Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> url = "http:\\python.com"
>>> print(f"{url.removeprefix('http:\\')}")
python.com
Python旧版 <=3.11, f-string 实现施加了一些限制:
- 无法重复使用引号或字符串分隔符
- 无法嵌入反斜杠,这意味着不能使用转义字符
- 禁止添加内联注释
- f-string 的嵌套仅限于 Python 中可用的引用变体
请使用 Python 3.12+
Python 3.12 有什么新功能
Python 3.12 语言变更主要集中在可用性,因为 f-字串已经移除了许多限制.
PEP 701: Syntactic formalization of f-strings
PEP 701 lifts some restrictions on the usage of f-strings. Expression components inside f-strings can now be any valid Python expression, including strings reusing the same quote as the containing f-string, multi-line expressions, comments, backslashes, and unicode escape sequences.
Python旧版 <=3.11, f-string 实现施加了一些限制:
请使用 Python 3.12+
Python 3.12 有什么新功能
Python 3.12 语言变更主要集中在可用性,因为 f-字串已经移除了许多限制.
PEP 701: Syntactic formalization of f-strings
PEP 701 lifts some restrictions on the usage of f-strings. Expression components inside f-strings can now be any valid Python expression, including strings reusing the same quote as the containing f-string, multi-line expressions, comments, backslashes, and unicode escape sequences.