Python line splitting and removing spaces

I would like to separate String by a comma ','and remove spaces from the beginning and end of each separation.

For example, if I have a line:

"QVOD, Baidu Player"

I would like to split and split into:

['QVOD', 'Baidu Player']

Is there an elegant way to do this? Perhaps using list comprehension?

+4
source share
2 answers

Python has a spectacular function splitthat won't let you use a regex or something like that. You can split your line just by callingmy_string.split(delimiter)

After that, python has a function stripthat will remove all spaces from the beginning and end of the line.

[item.strip() for item in my_string.split(',')]

:

>>> import timeit
>>> timeit.timeit('map(str.strip, "QVOD, Baidu Player".split(","))', number=100000)
0.3525350093841553
>>> timeit.timeit('map(stripper, "QVOD, Baidu Player".split(","))','stripper=str.strip', number=100000)
0.31575989723205566
>>> timeit.timeit("[item.strip() for item in 'QVOD, Baidu Player'.split(',')]", number=100000)
0.246596097946167

, comp 33% , .

, , , "", LC. http://www.artima.com/weblogs/viewpost.jsp?thread=98196

+9

. split, ,, str.strip, map.

>>> stripper = str.strip
>>> map(stripper, "QVOD, Baidu Player".split(","))
['QVOD', 'Baidu Player']

import timeit
stripper = str.strip
print timeit.timeit('map(stripper, "QVOD, Baidu Player".split(","))', "from __main__ import stripper", number=100000)
print timeit.timeit("[item.strip() for item in 'QVOD, Baidu Player'.split(',')]", number=100000)

0.553178071976
0.569463968277

, List List map .

+4

All Articles