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.
One liner. Just concatenate all but the last element with ,
as the delimiter. Then just append &
and then the last element finally to the end.
print ', '.join(lst[:-1]) + ' & ' + lst[-1]
If you wish to handle empty lists or such:
if len(lst) > 1:
print ', '.join(lst[:-1]) + ' & ' + lst[-1]
elif len(lst) == 1:
print lst[0]
You can simply use Indexng and F-strings (Python-3.6+):
In [1]: l=['Jim','Dave','James','Laura','Kasra']
In [3]: ', '.join(l[:-1]) + f' & {l[-1]}'
Out[3]: 'Jim, Dave, James, Laura & Kasra'