Skip to content

Instantly share code, notes, and snippets.

@fletom
Created November 28, 2012 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fletom/4164773 to your computer and use it in GitHub Desktop.
Save fletom/4164773 to your computer and use it in GitHub Desktop.
Python language code
def english_count(count, object = None, plural = None):
"""
Generate an English representation of the count of objects. Plural defaults to object + 's' or object[:-1] + 'ies' for objects ending in 'y'.
Examples:
In [2]: english_count(0, 'hat')
Out[2]: 'no hats'
In [4]: english_count(1, 'hat')
Out[4]: '1 hat'
In [5]: english_count(3, 'pastry')
Out[5]: '3 pastries'
In [2]: english_count(4, 'knife', 'knives')
Out[2]: '4 knives'
"""
text = 'no' if count == 0 else str(count)
if object is not None:
if plural is None:
if object[-1] == 'y':
plural = object[:-1] + 'ies'
else:
plural = object + 's'
text += ' ' + (object if count == 1 else plural)
return text
def english_list(items, and_or = 'and'):
"""
Generate an English representation of a list of things. Defaults to 'and' but you can also pass 'or' as the second argument.
Examples:
In [3]: english_list(string.uppercase)
Out[3]: 'A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z'
In [4]: english_list(['A', 'B'], 'or')
Out[4]: 'A or B'
In [6]: english_list(['A'])
Out[6]: 'A'
In [7]: english_list([])
Out[7]: ''
"""
items = [str(item) for item in items]
if len(items) < 3:
# Handles the edgecases of zero, one, and two items ('', 'A', 'A and B' respectively)
text = (' ' + and_or + ' ').join(items)
else:
separator = ', '
text = separator.join(items[:-1])
text += separator + and_or + ' ' + str(items[-1])
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment