Created
April 27, 2011 21:47
-
-
Save idmillington/945295 to your computer and use it in GitHub Desktop.
Separates a list of strings with the given separator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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