p priyanka p priyanka - 10 months ago 89
Python Question

Strip spaces from a list of tuples

I have a list of tuples like

[('Parrish', 'Alabama'), ('Phil Campbell', 'Alabama'), ('Lisman', 'Alabama')]

I wanted to strip off the spaces and i wanted the output to be in the form of


Also i have a list like this below, how to split the second element in list

['28/08/17','Parrish,Alabama', '33.7306642', '-87.2844473', ' Ground Snow Load is10 psf']

My output should be in the form of

['28/08/17','Parrish', 'Alabama', '33.7306642', '-87.2844473', ' Ground Snow Load is10 psf']

Answer Source

Version 3

You can use a list comprehension with ','.join. Use str.replace to remove spaces after the join is complete.

In [86]: [','.join(y).replace(' ', '')  for y in lst]
Out[86]: ['Parrish,Alabama', 'PhilCampbell,Alabama', 'Lisman,Alabama']

Readability improved thanks to no1xsyzy and Jon Clements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download