为什么 f'{{{74}}}' 与 f'{{74}}' 与 f-Strings 相同?

fed*_*qui 111 python string formatting python-3.x f-string

f-Strings在 Python 3.6 中可用,对于格式化字符串非常有用:

>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'
Run Code Online (Sandbox Code Playgroud)

Python 3 的 f-Strings: An Improvement String Formatting Syntax (Guide) 中阅读更多关于它们的信息。我发现了一个有趣的模式:

请注意,使用三个大括号将导致您的字符串中只有一个大括号:

>>> f"{{{74}}}"
'{74}'
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用三个以上的大括号,您可以获得更多的大括号来显示:

>>> f"{{{{74}}}}"
'{{74}}'
Run Code Online (Sandbox Code Playgroud)

情况正是如此:

>>> f'{74}'
'74'

>>> f'{{74}}'
'{74}'
Run Code Online (Sandbox Code Playgroud)

现在如果我们从二{传到三,结果是一样的:

>>> f'{{{74}}}'
'{74}'           # same as f'{{74}}' !
Run Code Online (Sandbox Code Playgroud)

所以我们最多需要4个!( {{{{) 得到两个大括号作为输出:

>>> f'{{{{74}}}}'
'{{74}}'
Run Code Online (Sandbox Code Playgroud)

为什么是这样?从那一刻起,用两个大括号让 Python 需要一个额外的大括号会发生什么?

Kon*_*lph 120

双大括号避开大括号,因此不会发生插值:{{? {, 和}}? }. 并74保持不变的字符串,'74'

对于三重大括号,外部双大括号被转义,与上面相同。另一方面,内部大括号导致 value 的常规字符串插值74

也就是说,字符串f'{{{74}}}'等效于f'{{ {74} }}',但没有空格(或等效于'{' + f'{74}' + '}')。

您可以看到用变量替换数字常量时的区别:

In [1]: x = 74

In [2]: f'{{x}}'
Out[2]: '{x}'

In [3]: f'{{{x}}}'
Out[3]: '{74}'
Run Code Online (Sandbox Code Playgroud)