我有一些python代码,分隔逗号,但不剥离空白:

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

我宁愿最后像这样删除空白:

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

我知道我可以循环遍历列表并strip()每个项,但由于这是Python,我猜有一种更快、更简单和更优雅的方式来完成它。


当前回答

Map (lambda s: s.strip(), mylist)会比显式循环好一点。或者一次性获取全部:map(lambda s:s.strip(), string.split(','))

其他回答

Map (lambda s: s.strip(), mylist)会比显式循环好一点。或者一次性获取全部:map(lambda s:s.strip(), string.split(','))

使用列表推导式——更简单,和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文档中的列表理解 一个很好的2秒列表理解的解释。

import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

简单地说,逗号或至少一个空格,前面/后面没有空格。

请尝试!

在分割字符串之前,只需删除字符串中的空白。

mylist = my_string.replace(' ','').split(',')
import re
result=[x for x in re.split(',| ',your_string) if x!='']

这对我来说很好。