Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have some python code that splits on a comma, but doesn't strip the whitespace:

>>> string = "blah, lots , of , spaces, here " 

>>> mylist = string.split(',') 

>>> print mylist ['blah', ' lots ', ' of ', ' spaces', ' here ']

I would rather end up with whitespace removed like this:

['blah', 'lots', 'of', 'spaces', 'here']

I am aware that I could loop through the list and strip() each item but, as this is Python, I'm guessing there's a quicker, easier and more elegant way of doing it.

1 Answer

0 votes
by (106k points)

You can use list comprehension which is simpler, and just as easy to read as a for loop. See the code below:-

my_string = "blah, lots , of , spaces, here " 

result = [x.strip() for x in my_string.split(',')] 

Browse Categories

...