python字符串剔除空格和逗号_用逗号分隔并在Python中删除空格

用逗号分隔并在Python中删除空格我有一些python代码分裂逗号,但不剥离空格:>>> string = "blah, lots , of , spaces, here ">>> mylist = string.split(',')>>> print mylist['blah', ' lots ', ' of ', ' spac...
摘要由CSDN通过智能技术生成

用逗号分隔并在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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值