我有一些python代码,分隔逗号,但不剥离空白:
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
我宁愿最后像这样删除空白:
['blah', 'lots', 'of', 'spaces', 'here']
我知道我可以循环遍历列表并strip()每个项,但由于这是Python,我猜有一种更快、更简单和更优雅的方式来完成它。
使用列表推导式——更简单,和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
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
s匹配任何空白字符,我们只是用一个空字符串替换它。你可以在这里找到更多信息:http://docs.python.org/library/re.html#re.sub