iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python String Formatting

Python has three ways to interpolate values into strings. f-strings (3.6+) are the modern default.

f-strings

PYTHON
name = 'Ada'
age  = 36
print(f'{name} is {age}')              # Ada is 36
print(f'{name!r}')                      # 'Ada'  — repr
print(f'{1/3:.4f}')                     # 0.3333 — fixed
print(f'{42:08d}')                      # 00000042 — zero pad
print(f'{name:>10}')                    # right-align 10 wide

str.format

PYTHON
'{} is {}'.format(name, age)
'{n} is {a}'.format(n=name, a=age)
'{0} {1} {0}'.format('ha', 'lol')      # repeat positional

%-formatting (legacy)

PYTHON
'%s is %d' % (name, age)

Format spec mini-language

SpecMeans
.2fFloat with 2 decimal places.
e / EScientific notation.
d / b / o / xInt as dec / bin / oct / hex.
,Thousands separator.
%Percent (value × 100).
> < ^Right / left / centre align.
PYTHON
price = 1234567.891
print(f'{price:,.2f}')      # 1,234,567.89
print(f'{0.27:.0%}')        # 27%
print(f'{255:#04x}')         # 0xff

f-strings can debug

PYTHON
x = 7
print(f'{x=}')           # x=7  — handy for prints
Tip: Don't build SQL or HTML by f-stringing user input. Use parameter binding (SQL) or templating libraries (HTML) — they prevent injection.

Example

Example
name = 'Ada'
age = 36
print(f'{name} is {age}')               # f-string
print('{} is {}'.format(name, age))     # str.format
print('%s is %d' % (name, age))         # printf-style
Try it Yourself »

Exercise

A modern f-string that shows pi to two decimals.

f'{math.pi: }'

Test yourself

Q1. The modern default formatter is…
Q2. f'{x=}' is useful for…
Q3. For HTML/SQL with user input prefer…

Discussion

Loading…