F-strings¶

Python 3.6 introduced another way to format objectsas strings: f-strings.

We prefix a string with f and include format specifiers within the string.

For example if x=5.6 then the string f"The value of x is {x}" would have the value "The value of x is 5.6" when the value of the string literal is evaluated.

In [3]:
x=5.6
s = f"The value of x is {x}"
print(s)
x=1.0
print(s)
The value of x is 5.6
The value of x is 5.6

We can include all of the usual format specifiers:

In [13]:
s="Hello, world!"
f"The value of x is {x:08.3f} and the value of s is =>{s:>20}<="
Out[13]:
'The value of x is 0005.600 and the value of s is =>       Hello, world!<='