TExcelTAD
Home › Python › Python String Formatting

Python String Formatting

Programs constantly build text out of values: "Total: 12.50 USD", "3 files copied". Python has several ways to do this, but the modern, recommended one is the f-string (formatted string literal), available since Python 3.6.

f-strings

Put an f before the opening quote and write any expression inside {}. Python evaluates it and inserts the result:

python · try it yourself
name = "Linh"
items = 3
price = 2.5
print(f"Hi {name}, you bought {items} items.")
print(f"Total: {items * price} USD")
print(f"Name in capitals: {name.upper()}")
Hi Linh, you bought 3 items.
Total: 7.5 USD
Name in capitals: LINH

Format specifiers

After the expression you can add a colon : and a format spec that controls how the value looks.

Decimal places and thousands separators

python · try it yourself
pi = 3.14159265
salary = 1234567.891
print(f"{pi:.2f}")          # 2 decimal places
print(f"{pi:.4f}")
print(f"{salary:,.2f}")     # comma as thousands separator
print(f"{salary:_.0f}")     # underscore separator, no decimals
print(f"{0.257:.1%}")       # percentage
print(f"{1500000:.2e}")     # scientific notation
3.14
3.1416
1,234,567.89
1_234_568
25.7%
1.50e+06

Width and alignment

< aligns left, > right and ^ centre. A character before the arrow is used as padding:

python · try it yourself
for fruit, qty in [("apple", 3), ("banana", 12), ("kiwi", 150)]:
    print(f"|{fruit:<8}|{qty:>5}|")

print(f"[{'title':^11}]")
print(f"[{'title':*^11}]")
print(f"{7:03d}")           # zero-pad to width 3
|apple   |    3|
|banana  |   12|
|kiwi    |  150|
[   title   ]
[***title***]
007

Number bases

python · try it yourself
n = 255
print(f"{n:b} {n:o} {n:x} {n:X}")
print(f"{n:#x} {n:#b}")
11111111 377 ff FF
0xff 0b11111111

Format spec cheat sheet

Spec Meaning Example Output
.2f fixed, 2 decimals f"{2/3:.2f}" 0.67
, thousands separator f"{10000:,}" 10,000
% percentage f"{0.5:%}" 50.000000%
>10 right-align in 10 chars f"{'x':>3}" x
^10 centre f"{'x':^3}" x
05d zero-pad integer f"{42:05d}" 00042
x / b hex / binary f"{10:b}" 1010

Debugging with =

Adding = after an expression prints both the expression and its value — very handy while debugging (Python 3.8+):

python · try it yourself
width = 4
height = 7
print(f"{width=}, {height=}, {width * height=}")
width=4, height=7, width * height=28

Literal braces and quotes

Double the braces to print them literally. Inside the braces, use the other kind of quote than the one around the f-string (Python 3.12 relaxes this rule, but older versions require it):

python · try it yourself
data = {"city": "Hue"}
print(f"{{braces}} and {data['city']}")
{braces} and Hue

Older styles you will still see

Before f-strings, Python code used str.format() and the % operator. You'll meet both in older code, so it's good to recognise them:

python · try it yourself
name, score = "Tuan", 91.456
print("{} scored {:.1f}".format(name, score))
print("{1} before {0}".format("second", "first"))
print("%s scored %.1f" % (name, score))
Tuan scored 91.5
first before second
Tuan scored 91.5

format() is still useful when the template is stored separately from the values, for example in a configuration file.

Tip: Format specs work in all three styles, and also with the built-in format(value, spec) function: format(3.14159, ".2f") returns '3.14'.

Test yourself

What does f"{3.14159:.2f}" produce?

  1. 3.14159
  2. 3.1
  3. 3.14
  4. 3.142

What does f"{x=}" print when x = 5?

  1. 5
  2. x=5
  3. {x=}
  4. x = 5

How do you include a literal { in an f-string?

  1. \{
  2. {{
  3. {'{'}
  4. It's impossible