Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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
like image 256
Shameem Avatar asked Jan 18 '26 15:01

Shameem


2 Answers

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.

like image 151
niemmi Avatar answered Jan 20 '26 06:01

niemmi


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 )
like image 37
backtrack Avatar answered Jan 20 '26 05:01

backtrack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!