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

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

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

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

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


当前回答

使用正则表达式进行拆分。注意,我用前导空格使情况更一般。列表推导式是删除前面和后面的空字符串。

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

看到前面的空格了吗?

澄清:上面使用的是Python 3解释器,但在Python 2中结果相同。

其他回答

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

拖鞋!

s = 'bla, buu, jii'

sp = []
sp = s.split(',')
for st in sp:
    print st
import re
result=[x for x in re.split(',| ',your_string) if x!='']

这对我来说很好。

使用列表推导式——更简单,和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)]

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

请尝试!