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?
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)
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.
4.1.We can use any quotation marks {single or double or triple} in the f-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.
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With