Why is f'{{{74}}}' the same as f'{{74}}' with f-Strings?

Question:

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?

Asked By: fedorqui

||

Answers:

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}'
Answered By: Konrad Rudolph