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
| Spec | Means |
|---|---|
.2f | Float with 2 decimal places. |
e / E | Scientific notation. |
d / b / o / x | Int 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:
}'
A format spec — dot two f.
Discussion
Loading…