问题:为什么带有f字符串的f'{{{74}}}’与f'{{74}}’相同?

f字符串可从Python 3.6中获得,对于格式化字符串非常有用:

>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'

Python 3的f字符串中阅读有关它们的更多信息:改进的字符串格式语法(指南)。我发现了一个有趣的模式:

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

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

但是,如果使用的括号多于三个,则可以显示更多的括号:

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

确实是这样:

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

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

现在,如果我们从两个传递{到三个,结果将是相同的:

>>> f'{{{74}}}'
'{74}'           # same as f'{{74}}' !

因此,我们最多需要4个!({{{{)获得两个大括号作为输出:

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

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

f-Strings are available from Python 3.6 and are very useful for formatting strings:

>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'

Reading more about them in Python 3’s f-Strings: An Improved String Formatting Syntax (Guide). I found an interesting pattern:

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}}'

And this is exactly the case:

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

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

Now if we pass from two { to three, the result is the same:

>>> f'{{{74}}}'
'{74}'           # same as f'{{74}}' !

So we need up to 4! ({{{{) to get two braces as an output:

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

Why is this? What happens with two braces to have Python require an extra one from that moment on?


回答 0

双括号逃脱牙套,所以没有发生插值:{{{}}}。并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}'

Double braces escape the braces, so that no interpolation happens: {{{, and }}}. And 74 remains an unchanged string, '74'.

With triple braces, the outer double braces are escaped, same as above. The inner braces, on the other hand, lead to regular string interpolation of the value 74.

That is, the string f'{{{74}}}' is equivalent to f'{{ {74} }}', but without spaces (or, equivalently, to '{' + f'{74}' + '}').

You can see the difference when replacing the numeric constant by a variable:

In [1]: x = 74

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

In [3]: f'{{{x}}}'
Out[3]: '{74}'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。