-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathformat_list.py
More file actions
36 lines (24 loc) · 906 Bytes
/
format_list.py
File metadata and controls
36 lines (24 loc) · 906 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""List formatting"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
__all__ = ["and_list", "or_list"]
def or_list(items: Sequence[str]) -> str:
"""Given [ A, B, C ] return 'A, B, or C'."""
return format_list("or", items)
def and_list(items: Sequence[str]) -> str:
"""Given [ A, B, C ] return 'A, B, and C'."""
return format_list("and", items)
def format_list(conjunction: str, items: Sequence[str]) -> str:
"""Given [ A, B, C ] return 'A, B, (conjunction) C'"""
if not items:
msg = "Missing list items to be formatted."
raise ValueError(msg)
n = len(items)
if n == 1:
return items[0]
if n == 2:
return f"{items[0]} {conjunction} {items[1]}"
*all_but_last, last_item = items
return f"{', '.join(all_but_last)}, {conjunction} {last_item}"