Shameem PKS Shameem PKS - 19 days ago 6
Python Question

How to separate Python list of strings using comma and ampersand depending length ?



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


Thanks in advance

Answer

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.

Comments