I want to separate Python list of strings using comma and ampersand depending length.
For example
>>> my_list = ['a']
>>> foo(my_list)
a
>>> my_list = ['a', 'b']
>>> foo(my_list)
a & b
>>> my_list = ['a', 'b', 'c']
>>> foo(my_list)
a, b & c
You can use following one liner:
>>> l = ['a', 'b', 'c']
>>> ' & '.join(', '.join(l).rsplit(', ', 1))
'a, b & c'
It will join all the items with ', ', then split from last ', ' and join again with ' & '. It only works if your items don't contain ', ' though.
ll = ['a']
length = len(ll)
if length >1 :
output_str = ', '.join(ll[:-1])
output_str = output_str + ' & ' +ll[length-1]
else:
output_str = ''.join(ll)
print(output_str )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With