Search code examples
pythonlistsplitwhitespacestrip

How to split by comma and strip white spaces in Python?


I have some python code that splits on 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.


Solution

  • Use list comprehension -- simpler, and just as easy to read as a for loop.

    my_string = "blah, lots  ,  of ,  spaces, here "
    result = [x.strip() for x in my_string.split(',')]
    # result is ["blah", "lots", "of", "spaces", "here"]
    

    See: Python docs on List Comprehension
    A good 2 second explanation of list comprehension.