I\'m trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g.
It looks like while I was working on my answer, someone may have beaten me to the punch with a similar one. Here's mine for comparison. Note that this also handles cases of 0, 1, or 2 members in the list.
# Python 3.x, should also work with Python 2.x.
def my_join(my_list):
x = len(my_list)
if x > 2:
s = ', & '.join([', '.join(my_list[:-1]), my_list[-1]])
elif x == 2:
s = ' & '.join(my_list)
elif x == 1:
s = my_list[0]
else:
s = ''
return s
assert my_join(['Jim', 'Jack', 'John']) == 'Jim, Jack, & John'
assert my_join(['Jim', 'Jack']) == 'Jim & Jack'
assert my_join(['Jim',]) == 'Jim'
assert my_join([]) == ''