Skip to content

Commit 6eb4231

Browse files
committed
feat: add conjunction parameter to natural_list
1 parent 392aef7 commit 6eb4231

2 files changed

Lines changed: 25 additions & 5 deletions

File tree

‎src/humanize/lists.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@
1010
__all__ = ["natural_list"]
1111

1212

13-
def natural_list(items: Iterable[Any]) -> str:
13+
def natural_list(items: Iterable[Any], *, conjunction: str = "and") -> str:
1414
"""Natural list.
1515
16-
Convert an iterable of items into a human-readable string with commas and 'and'.
16+
Convert an iterable of items into a human-readable string with commas and a
17+
conjunction.
1718
1819
Examples:
1920
>>> natural_list(["one", "two", "three"])
@@ -22,19 +23,22 @@ def natural_list(items: Iterable[Any]) -> str:
2223
'one and two'
2324
>>> natural_list(["one"])
2425
'one'
26+
>>> natural_list(["one", "two", "three"], conjunction="or")
27+
'one, two or three'
2528
2629
Args:
2730
items (Iterable): An iterable of items.
31+
conjunction (str): The word used to join the last item, defaults to 'and'.
2832
2933
Returns:
30-
str: A string with commas and 'and' in the right places.
34+
str: A string with commas and the conjunction in the right places.
3135
"""
3236
item_list = [str(item) for item in items]
3337
if not item_list:
3438
return ""
3539
if len(item_list) == 1:
3640
return item_list[0]
3741
elif len(item_list) == 2:
38-
return f"{item_list[0]} and {item_list[1]}"
42+
return f"{item_list[0]} {conjunction} {item_list[1]}"
3943
else:
40-
return ", ".join(item_list[:-1]) + f" and {item_list[-1]}"
44+
return ", ".join(item_list[:-1]) + f" {conjunction} {item_list[-1]}"

‎tests/test_lists.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,19 @@
2929
)
3030
def test_natural_list(test_args: Iterable[Any], expected: str) -> None:
3131
assert humanize.natural_list(*test_args) == expected
32+
33+
34+
@pytest.mark.parametrize(
35+
"items, conjunction, expected",
36+
[
37+
(["one", "two", "three"], "or", "one, two or three"),
38+
(["one", "two"], "or", "one or two"),
39+
(["one"], "or", "one"),
40+
(["one", "two", "three"], "and also", "one, two and also three"),
41+
(["one", "two", "three"], "and", "one, two and three"),
42+
],
43+
)
44+
def test_natural_list_conjunction(
45+
items: list[str], conjunction: str, expected: str
46+
) -> None:
47+
assert humanize.natural_list(items, conjunction=conjunction) == expected

0 commit comments

Comments
 (0)