Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Created February 18, 2023 02:40
Show Gist options
  • Save bpeterso2000/ad2adb353e017209a5ba9fc2cbe155f9 to your computer and use it in GitHub Desktop.
Save bpeterso2000/ad2adb353e017209a5ba9fc2cbe155f9 to your computer and use it in GitHub Desktop.
from math import log10
from typing import Sequence
def print_numbered_list(items: Sequence, fmt='{num}. {item}') -> None:
"""Display as a numbered list where the items are left aligned.
items:
A list of printable items.
fmt:
The output format where `num` will be right aligned and
`item` will be left aligned.
Note: Don't include alignments in the `fmt` string; they're
already done inside the function before it uses the format.
>>> items = [
... 'Cerium', 'Lanthanum', 'Neodynium', 'Yttirium', 'Praesodynium',
... 'Samarium', 'Gadolinium', 'Dysprosium', 'Erbium', 'Ytterbium'
... ]
>>> print_numbered_list(items)
1. Cerium
2. Lanthanum
3. Neodynium
4. Yttirium
5. Praesodynium
6. Samarium
7. Gadolinium
8. Dysprosium
9. Erbium
10. Ytterbium
>>> items = items[:2]
>>> print_numbered_list(items)
1. Cerium
2. Lanthanum
>>> print_numbered_list(items, fmt='{num} ... {item}')
1 ... Cerium
2 ... Lanthanum
"""
num_width = int(log10(len(items))) + 1
for num, item in enumerate(items, 1):
num =str(num).rjust(num_width)
print(fmt.format(num=num, item=item))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment