Split by comma and strip whitespace in Python
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Question
00:40 Accepted answer (Score 773)
01:05 Answer 2 (Score 45)
02:18 Answer 3 (Score 27)
03:09 Answer 4 (Score 23)
03:24 Thank you
--
Full question
https://stackoverflow.com/questions/4071...
Accepted answer links:
[Python docs on List Comprehension]: http://docs.python.org/tutorial/datastru...
[A good 2 second explanation of list comprehension.]: https://stackoverflow.com/questions/5013...
Answer 2 links:
[a comment]: https://stackoverflow.com/questions/4071...
[comment on the same answer]: https://stackoverflow.com/a/4071396/4071...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #whitespace #strip
#avk47
ACCEPTED ANSWER
Score 823
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.
ANSWER 2
Score 29
Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.
>>> import re
>>> string = " blah, lots , of , spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']
This works even if ^\s+ doesn't match:
>>> string = "foo, bar "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>
Here's why you need ^\s+:
>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
[' blah', 'lots', 'of', 'spaces', 'here']
See the leading spaces in blah?
Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.
ANSWER 3
Score 23
Just remove the white space from the string before you split it.
mylist = my_string.replace(' ','').split(',')
ANSWER 4
Score 14
I know this has already been answered, but if you end doing this a lot, regular expressions may be a better way to go:
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
The \s matches any whitespace character, and we just replace it with an empty string ''. You can find more info here: http://docs.python.org/library/re.html#re.sub