Skip to content

Instantly share code, notes, and snippets.

@idmillington
Created April 27, 2011 21:47
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 idmillington/945295 to your computer and use it in GitHub Desktop.
Save idmillington/945295 to your computer and use it in GitHub Desktop.
Separates a list of strings with the given separator.
def sep(text_list, mid_sep=', ', last_sep=' and '):
"""
Separates a list of strings or unicode with the given separator,
adding a different separator at the end.
This allows the simple generation of strings such as:
"A, B, C and D"
>>> sep([])
''
>>> sep(['A'])
'A'
>>> sep(['A', 'B'])
'A and B'
>>> sep(['A', 'B', 'C'])
'A, B and C'
>>> sep(['A', 'B', 'C'], "; ")
'A; B and C'
>>> sep(['A', 'B', 'C'], last_sep=" et ")
'A, B et C'
>>> sep(['A', 'B', 'C'], mid_sep="; ", last_sep=" et ")
'A; B et C'
"""
num_list = len(text_list)
if num_list == 0: return ''
if num_list == 1: return text_list[0]
if num_list == 2: return last_sep.join(text_list)
else:
return last_sep.join([mid_sep.join(text_list[:-1])] + text_list[-1:])
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment