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

浮云间
TA贡献1829条经验 获得超4个赞
使用列表理解-更简单,就像for循环一样容易阅读。
my_string = "blah, lots , of , spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]
添加回答
举报
0/150
提交
取消