Skip to content

Commit

Permalink
Add concatenate(serial_comma=True) option (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
xolox committed Nov 30, 2020
1 parent 9ae769b commit 8add138
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
2 changes: 2 additions & 0 deletions humanfriendly/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,8 @@ def test_concatenate(self):
assert concatenate(['one', 'two', 'three']) == 'one, two and three'
# Test the 'conjunction' option.
assert concatenate(['one', 'two', 'three'], conjunction='or') == 'one, two or three'
# Test the 'serial_comma' option.
assert concatenate(['one', 'two', 'three'], serial_comma=True) == 'one, two, and three'

def test_split(self):
"""Test :func:`humanfriendly.text.split()`."""
Expand Down
16 changes: 13 additions & 3 deletions humanfriendly/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def compact_empty_lines(text):
return ''.join(lines)


def concatenate(items, conjunction='and'):
def concatenate(items, conjunction='and', serial_comma=False):
"""
Concatenate a list of items in a human friendly way.
Expand All @@ -105,18 +105,28 @@ def concatenate(items, conjunction='and'):
The word to use before the last item (a string, defaults to "and").
:param serial_comma:
:data:`True` to use a `serial comma`_, :data:`False` otherwise
(defaults to :data:`False`).
:returns:
A single string.
>>> from humanfriendly.text import concatenate
>>> concatenate(["eggs", "milk", "bread"])
'eggs, milk and bread'
.. _serial comma: https://en.wikipedia.org/wiki/Serial_comma
"""
items = list(items)
if len(items) > 1:
last_item = items.pop()
return ' '.join([', '.join(items), conjunction, last_item])
final_item = items.pop()
formatted = ', '.join(items)
if serial_comma:
formatted += ','
return ' '.join([formatted, conjunction, final_item])
elif items:
return items[0]
else:
Expand Down

0 comments on commit 8add138

Please sign in to comment.