diff --git a/src/humanize/lists.py b/src/humanize/lists.py index 36e8ab73..03d7b0cf 100644 --- a/src/humanize/lists.py +++ b/src/humanize/lists.py @@ -10,10 +10,11 @@ __all__ = ["natural_list"] -def natural_list(items: Iterable[Any]) -> str: +def natural_list(items: Iterable[Any], *, conjunction: str = "and") -> str: """Natural list. - Convert an iterable of items into a human-readable string with commas and 'and'. + Convert an iterable of items into a human-readable string with commas and a + conjunction. Examples: >>> natural_list(["one", "two", "three"]) @@ -22,12 +23,15 @@ def natural_list(items: Iterable[Any]) -> str: 'one and two' >>> natural_list(["one"]) 'one' + >>> natural_list(["one", "two", "three"], conjunction="or") + 'one, two or three' Args: items (Iterable): An iterable of items. + conjunction (str): The word used to join the last item, defaults to 'and'. Returns: - str: A string with commas and 'and' in the right places. + str: A string with commas and the conjunction in the right places. """ item_list = [str(item) for item in items] if not item_list: @@ -35,6 +39,6 @@ def natural_list(items: Iterable[Any]) -> str: if len(item_list) == 1: return item_list[0] elif len(item_list) == 2: - return f"{item_list[0]} and {item_list[1]}" + return f"{item_list[0]} {conjunction} {item_list[1]}" else: - return ", ".join(item_list[:-1]) + f" and {item_list[-1]}" + return ", ".join(item_list[:-1]) + f" {conjunction} {item_list[-1]}" diff --git a/tests/test_lists.py b/tests/test_lists.py index 9b3c1b77..fcd91e7a 100644 --- a/tests/test_lists.py +++ b/tests/test_lists.py @@ -29,3 +29,19 @@ ) def test_natural_list(test_args: Iterable[Any], expected: str) -> None: assert humanize.natural_list(*test_args) == expected + + +@pytest.mark.parametrize( + "items, conjunction, expected", + [ + (["one", "two", "three"], "or", "one, two or three"), + (["one", "two"], "or", "one or two"), + (["one"], "or", "one"), + (["one", "two", "three"], "and also", "one, two and also three"), + (["one", "two", "three"], "and", "one, two and three"), + ], +) +def test_natural_list_conjunction( + items: list[str], conjunction: str, expected: str +) -> None: + assert humanize.natural_list(items, conjunction=conjunction) == expected