用逗号分隔并在Python中删除空格
我有一些python代码分裂逗号,但不剥离空格:
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
我宁愿最终删除这样的空格:
['blah', 'lots', 'of', 'spaces', 'here']
我知道我可以遍历列表和strip()每个项目,但是,因为这是Python,我猜测有更快,更简单,更优雅的方式。
11个解决方案
433 votes
使用列表理解 - 更简单,和for循环一样容易阅读。
my_string = "blah, lots , of , spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]
请参阅:List Comprehension上的Python文档
列表理解的2秒解释。
Sean Vieir