为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

万千封印 2019-10-14 14:31:13
我有一些在逗号处分割的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"]


查看完整回答
反对 回复 2019-10-14
  • 3 回答
  • 0 关注
  • 1173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信