Almost every program has to mix text with values: “Total: 148.50 taka”, “Rafi scored 92%”. Python offers three ways to do it. f-strings are the modern, recommended one; str.format() and the older % operator still appear in existing code. This lesson shows all three, plus the format codes for decimals, padding, alignment, commas and percentages.
In this lesson you will learn
- How to write f-strings
- Format codes for decimals, width, alignment and commas
- Percentages, hex and binary output
- The
str.format()method and%formatting - How to print neat columns
f-Strings and Format Codes
Put f before the quotes and any expression inside {} is evaluated. After a colon you can add a format code.
name = "Sadia"
score = 92.456
items = 3
print(f"{name} scored {score:.1f}")
print(f"{items} items cost {items * 49.5:.2f} taka")
print(f"{'left':<8}|{'right':>8}|{'mid':^8}|")
print(f"{1234567:,}")
print(f"{0.256:.0%}")
print(f"{42:05d} {255:x} {5:b}")
print(f"{name=}")
Output
Sadia scored 92.5
3 items cost 148.50 taka
left | right| mid |
1,234,567
26%
00042 ff 101
name='Sadia'
| Code | Meaning | Example result |
|---|---|---|
:.1f, :.2f | Fixed decimals (rounded) | 92.5 |
:<8, :>8, :^8 | Left, right, centre in 8 characters | left |
:, | Thousands separator | 1,234,567 |
:.0% | Multiply by 100 and add % | 26% |
:05d | Pad an integer with zeros to width 5 | 00042 |
:x, :b | Hexadecimal, binary | ff, 101 |
{name=} (Python 3.8+) prints both the expression and its value, which is handy for quick debugging.
str.format(), % and Tidy Columns
print("{} is {} years old".format("Arif", 24))
print("{1} before {0}".format("second", "first"))
print("{city}: {temp}°C".format(city="Dhaka", temp=31))
print("%s has %d apples" % ("Nila", 5))
print("%.2f" % 3.14159)
rows = [("Rice", 75), ("Lentils", 120), ("Oil", 185)]
for item, price in rows:
print(f"{item:<10}{price:>6}")
Output
Arif is 24 years old
first before second
Dhaka: 31°C
Nila has 5 apples
3.14
Rice 75
Lentils 120
Oil 185
"{} {}".format(a, b)fills placeholders in order; numbers like{1}pick by position; names like{city}pick by keyword. The same format codes work after a colon."%s %d" % (a, b)is the oldest style, from C’sprintf.%smeans string,%dinteger,%.2fa float with two decimals.- Combining
:<10and:>6lines up text and numbers in neat columns.
Common Mistakes
- Forgetting the
f, which prints the braces literally. - Using the same quote type inside an f-string on Python before 3.12:
f"{d["key"]}"fails there. Usef"{d['key']}". - Writing a literal brace. Double it:
f"{{x}}"prints{x}. - Applying
:dto a float, which raisesValueError. Use:.0f.
Practice Exercises
Exercise 1. Print price = 1499.5 as Price: 1,499.50.
Show answer
price = 1499.5
print(f"Price: {price:,.2f}")
Exercise 2. Show 7 correct answers out of 9 as a percentage with one decimal.
Show answer
print(f"{7 / 9:.1%}") # 77.8%
Frequently Asked Questions
Which string formatting method should I use?
Use f-strings for new code: they are the most readable and the fastest. Use str.format() when the template is stored separately from the values, for example in a settings file.
Does :.2f round or cut off the number?
It rounds to the nearest value, using the usual floating-point rules.
Summary
- f-strings evaluate
{expression}inside the text. - Format codes after a colon control decimals, width, alignment, commas and percentages.
str.format()and%do the same job in older code.- Width and alignment codes make neat tables.
Related: Python Strings.
