408

我有一些以逗号分隔的 python 代码,但不删除空格:

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

我宁愿像这样删除空格:

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

我知道我可以遍历 list 和 strip() 每个项目,但是,因为这是 Python,我猜有一种更快、更简单、更优雅的方法。

4

11 回答 11

724

使用列表推导——更简单,就像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 秒很好的解释。

于 2010-11-01T17:30:38.607 回答
32

我来补充:

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

但看到 Jason Orendorff 在评论中已经提到了它。

阅读 Glenn Maynard对同一答案的评论,建议对地图进行列表理解,我开始想知道为什么。我认为他的意思是出于性能原因,但当然他可能是出于文体原因或其他原因(格伦?)。

因此,对我的盒子(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),但对我来说,它至少与列表理解一样清晰。

于 2013-02-28T14:25:23.683 回答
26

使用正则表达式拆分。请注意,我使用前导空格使情况更普遍。列表推导是去除前后的空字符串。

>>> 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 中是相同的。

于 2012-10-06T13:18:58.050 回答
20

只需在拆分之前从字符串中删除空格。

mylist = my_string.replace(' ','').split(',')
于 2010-11-01T18:26:37.143 回答
13

我知道这已经得到了回答,但如果你经常这样做,正则表达式可能是一个更好的方法:

>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']

匹配任何空白字符,我们只需将\s其替换为空字符串''。你可以在这里找到更多信息:http: //docs.python.org/library/re.html#re.sub

于 2012-02-01T05:30:22.760 回答
3

map(lambda s: s.strip(), mylist)会比显式循环好一点。或者一次性完成整个事情:map(lambda s:s.strip(), string.split(','))

于 2010-11-01T17:31:29.500 回答
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可以解决问题:

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

瞧!

于 2015-03-16T07:57:52.000 回答
2
import re
result=[x for x in re.split(',| ',your_string) if x!='']

这对我来说很好。

于 2015-06-02T11:57:50.057 回答
1
s = 'bla, buu, jii'

sp = []
sp = s.split(',')
for st in sp:
    print st
于 2015-01-31T02:15:33.683 回答
1
import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

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

请试试!

于 2017-04-26T06:59:22.677 回答
0

您可以先处理它然后再拆分它,而不是先拆分字符串然后担心空白

string.replace(" ", "").split(",")
于 2021-07-28T11:42:41.923 回答