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

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

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

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

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


当前回答

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

mylist = my_string.replace(' ','').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)]

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

请尝试!

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

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

这对我来说很好。

Re(在正则表达式中)允许同时对多个字符进行拆分:

$ string = "blah, lots  ,  of ,  spaces, here "
$ re.split(', ',string)
['blah', 'lots  ', ' of ', ' spaces', 'here ']

这对于示例字符串不太适用,但是对于逗号分隔的列表很适用。对于示例字符串,可以结合re.split功能对正则表达式模式进行拆分,以获得“按此或按此拆分”的效果。

$ re.split('[, ]',string)
['blah',
 '',
 'lots',
 '',
 '',
 '',
 '',
 'of',
 '',
 '',
 '',
 'spaces',
 '',
 'here',
 '']

不幸的是,这很难看,但过滤器可以做到:

$ filter(None, re.split('[, ]',string))
['blah', 'lots', 'of', 'spaces', 'here']

拖鞋!