You know how to build strings with f-strings. Now you can control how the values look: width, alignment, fill characters, decimal places, and thousands separators.
The syntax lives inside the braces after a colon:
The syntax lives inside the braces after a colon:
{value:<10} means left-align in 10 spaces.Width and alignment
name = 'Ada'
count = 42
title = 'Python'
# left-align in width 10
print(f'[{name:<10}]') # [Ada ]
# right-align in width 5
print(f'[{count:>5}]') # [ 42]
# centre in width 20
print(f'[{title:^20}]') # [ Python ]
# a width is a minimum: longer text is never cut
print(f'[{title:<3}]') # [Python]Fill character and decimal places
n = 7
price = 19.5
ratio = 0.8342
# the _ only makes the number easier to read
total = 1_234_567
# fill with *, right-align in width 6
print(f'{n:*>6}') # *****7
# 2 decimal places (f is for fixed point)
print(f'{price:.2f}') # 19.50
# a percentage, one decimal place
print(f'{ratio:.1%}') # 83.4%
print(f'{total:,}') # 1,234,567
print(f'{total:,.2f}') # 1,234,567.00Zero padding and self-documenting debug
minute = 7
hour = 12
total = 4_805.93
city = 'Oslo'
# zero padding, like a clock
print(f'{hour:02d}:{minute:02d}') # 12:07
# = shows the name, then its value
print(f'{total=}') # total=4805.93
# text keeps its quotes
print(f'{city=}') # city='Oslo'{var=} shows the variable name and its valueBuilding an aligned table
rows = [
('Ada', 98.5),
('Grace', 102.34),
('Linus', 76.0)
]
table_lines = [f"{'Name':<10}{'Score':>8}"]
for name, score in rows:
# the same widths as the header
table_lines.append(f'{name:<10}{score:>8.2f}')
print('\n'.join(table_lines))
# Name Score
# Ada 98.50
# Grace 102.34
# Linus 76.00Older styles you will still see
# str.format()
name, score = 'Ada', 98.5
print('{} scored {:.1f}'.format(name, score))
# %-style (very old code)
age = 36
print('%s is %d years old' % (name, age))