Mr_*_*imp 312 python whitespace strip
我有一些python代码分裂逗号,但不剥离空格:
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
Run Code Online (Sandbox Code Playgroud)
我宁愿最终删除这样的空格:
['blah', 'lots', 'of', 'spaces', 'here']
Run Code Online (Sandbox Code Playgroud)
我知道我可以遍历列表和strip()每个项目,但是,因为这是Python,我猜测有更快,更简单,更优雅的方式.
Sea*_*ira 541
使用列表理解 - 更简单,就像for循环一样容易阅读.
my_string = "blah, lots , of , spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]
Run Code Online (Sandbox Code Playgroud)
请参阅: 列表理解上的Python文档列表理解
的2秒解释.
tbc*_*bc0 22
使用正则表达式拆分.注意我使用前导空格使案例更加通用.列表理解是删除前面和后面的空字符串.
>>> 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']
Run Code Online (Sandbox Code Playgroud)
即使^\s+不匹配,这也有效:
>>> string = "foo, bar "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>
Run Code Online (Sandbox Code Playgroud)
这就是你需要^\s +的原因:
>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
[' blah', 'lots', 'of', 'spaces', 'here']
Run Code Online (Sandbox Code Playgroud)
看到blah的领先空间?
澄清:上面使用Python 3解释器,但结果在Python 2中是相同的.
Sea*_*ean 15
我来补充一下:
map(str.strip, string.split(','))
但看到Jason Orendorff在评论中已经提到过它.
阅读格伦梅纳德在同一个答案中的评论,表明对地图的列表理解我开始想知道为什么.我认为他的出于性能原因,但当然他可能是出于文体原因或其他原因(格伦?).
所以在我的盒子上应用这三种方法的快速(可能有缺陷的?)测试显示:
[word.strip() for word in string.split(',')]
$ time ./list_comprehension.py
real 0m22.876s
map(lambda s: s.strip(), string.split(','))
$ time ./map_with_lambda.py
real 0m25.736s
map(str.strip, string.split(','))
$ time ./map_with_str.strip.py
real 0m19.428s
Run Code Online (Sandbox Code Playgroud)
做map(str.strip, string.split(','))赢家,但它似乎他们都在同一个球场.
当然,虽然出于性能原因,不一定要排除map(有或没有lambda),对我而言,它至少与列表理解一样清楚.
编辑:
Ubuntu 10.04上的Python 2.6.5
use*_*041 13
在拆分之前,只需从字符串中删除空格.
mylist = my_string.replace(' ','').split(',')
Run Code Online (Sandbox Code Playgroud)
Bra*_*ery 11
我知道这已经得到了回答,但是如果你结束这么做,正则表达式可能是一个更好的方法:
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
Run Code Online (Sandbox Code Playgroud)
将\s匹配任何空白字符,我们只是用一个空字符串替换它''.您可以在此处找到更多信息:http://docs.python.org/library/re.html#re.sub
map(lambda s: s.strip(), mylist)比显式循环要好一点。或者一次性完成整个事情:map(lambda s:s.strip(), string.split(','))
| 归档时间: |
|
| 查看次数: |
479700 次 |
| 最近记录: |