用逗号分割并在Python中去除空格

我有一些在逗号处分割的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,所以我猜有一种更快,更轻松和更优雅的方法。


万千封印
浏览 1174回答 3
3回答

浮云间

使用列表理解-更简单,就像for循环一样容易阅读。my_string = "blah, lots  ,  of ,  spaces, here "result = [x.strip() for x in my_string.split(',')]# result is ["blah", "lots", "of", "spaces", "here"]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python