如何在Python中按逗号分割并去除空格?

459 投票
10 回答
724415 浏览
提问于 2025-04-16 06:24

我有一些Python代码,它是用逗号来分割字符串的,但没有去掉空格:

>>> string = "blah, lots  ,  of ,  spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots  ', '  of ', '  spaces', ' here ']

我希望最后得到的结果是去掉空格的,像这样:

['blah', 'lots', 'of', 'spaces', 'here']

我知道我可以通过循环列表来对每个项目使用strip()函数去掉空格,但因为这是Python,我想应该有更快、更简单、更优雅的方法来做到这一点。

10 个回答

29

使用正则表达式来分割字符串。注意,我把情况考虑得更广泛了一些,包括了前面的空格。列表推导式是用来去掉前后空字符串的。

>>> 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']

即使 ^\s+ 不匹配,这个方法也能正常工作:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

这里是你为什么需要 ^\s+ 的原因:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

你看到“blah”前面的空格了吗?

说明:上面的内容使用的是Python 3解释器,但在Python 2中结果是一样的。

49

我想补充一下:

map(str.strip, string.split(','))

但我看到这个已经被Jason Orendorff在一个评论中提到过了。

阅读Glenn Maynard在同一个答案下的评论,他建议使用列表推导而不是map,我开始想为什么。他可能是出于性能考虑,但也有可能是出于风格上的原因,或者其他什么原因(Glenn?)。

所以我在我的电脑上(使用的是Ubuntu 10.04上的Python 2.6.5)做了一个快速的(可能有缺陷的)测试,循环应用了这三种方法,结果显示:

$ time ./list_comprehension.py  # [word.strip() for word in string.split(',')]
real    0m22.876s

$ time ./map_with_lambda.py     # map(lambda s: s.strip(), string.split(','))
real    0m25.736s

$ time ./map_with_str.strip.py  # map(str.strip, string.split(','))
real    0m19.428s

使用map(str.strip, string.split(','))的效果最好,虽然看起来它们的表现都差不多。

不过,map(无论有没有lambda)在性能上并不一定要被排除,对我来说,它至少和列表推导一样清晰。

815

使用列表推导式——这更简单,而且和for循环一样容易理解。

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

参考: Python文档中的列表推导式
一个关于列表推导式的简短解释。

撰写回答