Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by comma and strip whitespace 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.

like image 621
Mr_Chimp Avatar asked Nov 01 '10 17:11

Mr_Chimp


People also ask

How do you remove space after a comma in Python?

The + operator, also known as the string concatenation operator, can be used in this case to prevent unnecessary spacing between the values. It's a direct alternative to comma separation and can be used along with the print statement.

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you split a white space in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string after a comma in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .


1 Answers

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.

like image 61
Sean Vieira Avatar answered Sep 20 '22 23:09

Sean Vieira