用逗号分割并在 Python 中去除空格 [英] Split by comma and strip whitespace in Python

查看:110
本文介绍了用逗号分割并在 Python 中去除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用逗号分隔的 python 代码,但没有去除空格:

<预><代码>>>>string = "blah, lot , of , space, here ">>>mylist = string.split(',')>>>打印我的列表['等等','很多','of','空格','这里']

我宁愿像这样删除空格:

['blah', 'lots', 'of', 'spaces', 'here']

我知道我可以遍历 list 和 strip() 每个项目,但是,由于这是 Python,我猜有一种更快、更简单、更优雅的方法来做到这一点.

解决方案

使用列表推导式——更简单,就像 for 循环一样容易阅读.

my_string = "blah, lot , of , space, here "result = [x.strip() for x in my_string.split(',')]# 结果是 ["blah", "lots", "of", "spaces", "here"]

参见: 关于列表理解的 Python 文档
对列表理解的 2 秒解释.

I have some python code that splits on comma, but doesn't strip the whitespace:

>>> string = "blah, lots  ,  of ,  spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots  ', '  of ', '  spaces', ' here ']

I would rather end up with whitespace removed like this:

['blah', 'lots', 'of', 'spaces', 'here']

I am aware that I could loop through the list and strip() each item but, as this is Python, I'm guessing there's a quicker, easier and more elegant way of doing it.

解决方案

Use list comprehension -- simpler, and just as easy to read as a for loop.

my_string = "blah, lots  ,  of ,  spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]

See: Python docs on List Comprehension
A good 2 second explanation of list comprehension.

这篇关于用逗号分割并在 Python 中去除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆