Reading history

Python String Formatting: f-Strings, format() and %

3 min read 1 views

Learn Python string formatting: f-strings, format codes for decimals, padding, alignment, commas and percent, plus str.format() and % style.

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'
CodeMeaningExample result
:.1f, :.2fFixed decimals (rounded)92.5
:<8, :>8, :^8Left, right, centre in 8 charactersleft    
:,Thousands separator1,234,567
:.0%Multiply by 100 and add %26%
:05dPad an integer with zeros to width 500042
:x, :bHexadecimal, binaryff, 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’s printf. %s means string, %d integer, %.2f a float with two decimals.
  • Combining :<10 and :>6 lines up text and numbers in neat columns.

Common Mistakes

  1. Forgetting the f, which prints the braces literally.
  2. Using the same quote type inside an f-string on Python before 3.12: f"{d["key"]}" fails there. Use f"{d['key']}".
  3. Writing a literal brace. Double it: f"{{x}}" prints {x}.
  4. Applying :d to a float, which raises ValueError. 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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *