Python f-string: Format Numbers and Text
An f-string is a string with an f in front of the quote. Write a variable or an expression inside { } and it is replaced by its value. Write a format after a colon, as in {value:format}, and you can also set decimal places, width and alignment. You can use f-strings from Python 3.6.
f"text {value} text {value:format}"
Putting in values and expressions
Inside the braces you can write not only variables but also calculations and function calls. Add = at the end, as in {age=}, and it prints the name and the value together (from 3.8). To print a brace character itself, write it twice: {{, }}.
name = "Mina"age = 12print(f"{name} is {age}")print(f"next year: {age + 1}")print(f"{name.upper()} {len(name)}")print(f"{age=}")print(f"{{age}} -> {age}")Mina is 12
next year: 13
MINA 4
age=12
{age} -> 12
Decimal places: .2f
:.2f means print up to the second decimal place. Missing places are filled with 0, and extra places are rounded. An integer is printed as a decimal number too.
pi = 3.14159print(f"{pi:.2f}")print(f"{pi:.0f}")print(f"{2 / 3:.3f}")print(f"{5:.1f}")print(f"{0.256:.1%}")3.14 3 0.667 5.0 25.6%
The % format in the last line multiplies by 100 and adds %.
Fixed width and zero padding
The number after the colon is the width. :5d prints in a width of five, and :02d, with a 0 in front, fills the empty places with 0. Use it when you print times or dates. :, puts in a comma as the thousands separator.
h, m, s = 9, 5, 30print(f"{h}:{m:02d}:{s:02d}")print(f"[{42:5d}]")print(f"[{42:05d}]")print(f"{1234567:,}")print(f"{1234.5:,.2f}")9:05:30 [ 42] [00042] 1,234,567 1,234.50
A value longer than the width is not cut off. It is printed in full.
Left, right and center alignment
Write < (left), > (right) or ^ (center) before the width. If you write none of them, strings go to the left and numbers to the right. Put one character before the alignment symbol and the empty space is filled with that character.
items = [("apple", 3, 1.5), ("kiwi", 12, 0.25)]for name, n, price in items: print(f"{name:<8}{n:>4}{price:>8.2f}")print(f"[{'ab':^6}]")print(f"[{'ab':*>6}]")print(f"[{'ab':6}][{7:6}]")apple 3 1.50 kiwi 12 0.25 [ ab ] [****ab] [ab ][ 7]
To give the width as a variable, use one more pair of braces inside the format, as in f"{name:>{width}}".
Common mistakes
Leaving out the f in front
name = "Mina"
print("Hello, {name}")
→ It prints Hello, {name} as is, not Hello, Mina
There is no error, so it is easy to miss. Put f right before the quote: f"Hello, {name}".
Using .2f on a string you read as input
x = input()
print(f"{x:.2f}")
→ ValueError: Unknown format code 'f' for object of type 'str'
f and d are formats for numbers only. Convert to a number first with x = float(input()). The other way round, using :d on a decimal number gives the same kind of error.
When .2f rounds differently from what you expect
print(f"{0.125:.2f}")
print(f"{0.375:.2f}")
print(f"{2.675:.2f}")
→ 0.12, 0.38, 2.67 — with the rounding taught at school it would be 0.13, 0.38, 2.68
A value exactly in the middle goes to the even side (0.125 → 0.12, 0.375 → 0.38). And 2.675 is stored inside the computer as a value very slightly smaller than 2.675, so it becomes 2.67. For calculations where not even one digit may be wrong, such as money, use integers (in units such as cents) or the decimal module.
Using the same quotes inside the braces as outside
d = {"a": 1}
print(f"{d["a"]}")
→ From Python 3.12 it prints 1, but up to 3.11 it is a SyntaxError
This syntax was allowed in 3.12, so the result depends on the version. To make it run everywhere, use different quotes inside: f"{d['a']}".