用逗号分割并在Python中去除空格
发布于 2021-01-29 15:00:11
我有一些在逗号处分割的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,所以我猜有一种更快,更轻松,更优雅的方法。
关注者
0
被浏览
79
1 个回答
-
使用列表理解-更简单,就像
for
循环一样容易阅读。my_string = "blah, lots , of , spaces, here " result = [x.strip() for x in my_string.split(',')] # result is ["blah", "lots", "of", "spaces", "here"]