Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 261
fedorqui 'SO stop harming' Avatar asked Dec 16 '19 15:12

fedorqui 'SO stop harming'


People also ask

What does the F in F-string stand for?

In Python source code, an f-string is a literal string, prefixed with f , which contains expressions inside braces. The expressions are replaced with their values.” (Source)

What two symbols does an F-string work?

The f-strings have the f prefix and use {} brackets to evaluate values. Format specifiers for types, padding, or aligning are specified after the colon character; for instance: f'{price:. 3}' , where price is a variable name.

Do F-strings need double quotes?

4.1.We can use any quotation marks {single or double or triple} in the f-string.

Does F-string convert to string?

An f-string is syntax, not an object type. You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.


1 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}' 
like image 83
Konrad Rudolph Avatar answered Nov 15 '22 16:11

Konrad Rudolph