为什么 f'{{{74}}}' 与 f'{{74}}' 与 f-Strings 相同?
Why is f'{{{74}}}' the same as f'{{74}}' with f-Strings?
f-Strings 可从 Python 3.6 获得,对格式化字符串非常有用:
>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'
在 Python 3's f-Strings: An Improved String Formatting Syntax (Guide) 中阅读更多关于它们的信息。我发现了一个有趣的模式:
Note that using triple braces will result in there being only single braces in your string:
>>> f"{{{74}}}"
'{74}'
However, you can get more braces to show if you use more than triple braces:
>>> f"{{{{74}}}}"
'{{74}}'
事实确实如此:
>>> f'{74}'
'74'
>>> f'{{74}}'
'{74}'
现在如果我们从两个 {
传递到三个,结果是一样的:
>>> f'{{{74}}}'
'{74}' # same as f'{{74}}' !
所以我们最多需要 4 个! ({{{{
) 得到两个大括号作为输出:
>>> f'{{{{74}}}}'
'{{74}}'
这是为什么?从那一刻起,两个牙套 Python 需要一个额外的牙套会怎样?
双大括号转义大括号,因此不会发生插值:{{
➝ {
,以及 }}
➝ }
。 74
保持不变的字符串,'74'
.
用三重大括号,外面的双大括号被转义,同上。另一方面,内部大括号导致值 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}'
f-Strings 可从 Python 3.6 获得,对格式化字符串非常有用:
>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'
在 Python 3's f-Strings: An Improved String Formatting Syntax (Guide) 中阅读更多关于它们的信息。我发现了一个有趣的模式:
Note that using triple braces will result in there being only single braces in your string:
>>> f"{{{74}}}" '{74}'
However, you can get more braces to show if you use more than triple braces:
>>> f"{{{{74}}}}" '{{74}}'
事实确实如此:
>>> f'{74}'
'74'
>>> f'{{74}}'
'{74}'
现在如果我们从两个 {
传递到三个,结果是一样的:
>>> f'{{{74}}}'
'{74}' # same as f'{{74}}' !
所以我们最多需要 4 个! ({{{{
) 得到两个大括号作为输出:
>>> f'{{{{74}}}}'
'{{74}}'
这是为什么?从那一刻起,两个牙套 Python 需要一个额外的牙套会怎样?
双大括号转义大括号,因此不会发生插值:{{
➝ {
,以及 }}
➝ }
。 74
保持不变的字符串,'74'
.
用三重大括号,外面的双大括号被转义,同上。另一方面,内部大括号导致值 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}'