I would like to split a String by comma ','
and remove whitespace from the beginning and end of each split.
For example, if I have the string:
"QVOD, Baidu Player"
I would like to split and strip to:
['QVOD', 'Baidu Player']
Is there an elegant way of doing this? Possibly using a list comprehension?
Python has a spectacular function called
split
that will keep you from having to use a regex or something similar. You can split your string by just callingmy_string.split(delimiter)
After that python has a
strip
function which will remove all whitespace from the beginning and end of a string.Benchmarks for the two methods are below:
So the list comp is about 33% faster than the map.
Probably also worth noting that as far as being "pythonic" goes, Guido himself votes for the LC. http://www.artima.com/weblogs/viewpost.jsp?thread=98196
A little functional approach.
split
function, splits the string based on,
and the each and every element will be stripped bystr.strip
, bymap
.Little timing comparison
Output on my machine
So, both the List comprehension method and
map
method perform almost the same.