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'
print(f'[{name:<10}]') # [Ada ] left-align in width 10
print(f'[{count:>5}]') # [ 42] right-align in width 5
print(f'[{title:^20}]') # [ Python ] centre in width 20Fill character and decimal places
n = 7
price = 19.5
ratio = 0.8342
total = 1_234_567
print(f'{n:*>6}') # *****7 right-align in width 6, padded with *
print(f'{price:.2f}') # 19.50 two decimal places
print(f'{ratio:.1%}') # 83.4% a percentage, one decimal place
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
print(f'{hour:02d}:{minute:02d}') # clock-style zero padding -> 12:07
print(f'{total=}') # total=4805.93 the name, then its value{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:
table_lines.append(f'{name:<10}{score:>8.2f}') # same widths as the header
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))