Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

f-format (formatted string literals)

  • f

Since Python 3.6

name = "Foo Bar"
age = 42.12
pi = 3.141592653589793
r = 2

print(f"The user {name} was born {age} years ago.")
print(f"The user {name:10} was born {age} years ago.")
print(f"The user {name:>10} was born {age} years ago.")
print(f"The user {name:>10} was born {age:>10} years ago.")

print(f"PI is '{pi:.3}'.")   # number of digits (defaults n = number)
print(f"PI is '{pi:.3f}'.")  # number of digits after decimal point

print(f"Area is {pi * r ** 2}")
print(f"Area is {pi * r ** 2:.3f}")

The user Foo Bar was born 42.12 years ago.
The user Foo Bar    was born 42.12 years ago.
The user    Foo Bar was born 42.12 years ago.
The user    Foo Bar was born      42.12 years ago.
PI is '3.14'.
PI is '3.142'.
Area is 12.566370614359172
Area is 12.566