Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[strutils] implements natural_enumerate #359

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions boltons/strutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,37 @@ def pluralize(word):
return _match_case(orig_word, plural)


def natural_enumerate(sized_iterable, last_sep=' and ', sep=", ", wrap_item_with=""):
"""
Return a string with a natural enumeration of the given items.

>>> natural_enumerate(['a', 'b', 'c', 'd'])
'a, b, c and d'
>>> natural_enumerate(['a', 'b', 'c'], ' or ')
'a, b or c'
>>> natural_enumerate(['a', 'b', 'c'], ', ')
'a, b, c'
>>> natural_enumerate(['a', 'b'], ' or ')
'a or b'
>>> natural_enumerate(['a'])
'a'
>>> natural_enumerate([])
''
>>> natural_enumerate(['a', 'b'], wrap_item_with="`")
'`a` and `b`'
>>> natural_enumerate(['a', 'b', 'c', 'd'], " = ", sep=" + ")
'a + b + c = d'
"""
if len(sized_iterable) == 0:
return ""
if wrap_item_with:
sized_iterable = [f"{wrap_item_with}{item}{wrap_item_with}" for item in sized_iterable]
if len(sized_iterable) == 1:
return sized_iterable[0]
all_but_last = sep.join(i for i in sized_iterable[:-1])
return f"{all_but_last}{last_sep}{sized_iterable[-1]}"


def _match_case(master, disciple):
if not master.strip():
return disciple
Expand Down
Loading