本文翻译自:Split by comma and strip whitespace in Python

I have some python code that splits on comma, but doesn't strip the whitespace: 我有一些在逗号处分割的python代码,但没有去除空格:

>>> 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. 我知道我可以遍历list和strip()每个项目,但是,因为这是Python,所以我猜有一种更快,更轻松和更优雅的方法。


#1楼

参考:https://stackoom.com/question/H59g/用逗号分割并在Python中去除空格


#2楼

Split using a regular expression. 使用正则表达式拆分。 Note I made the case more general with leading spaces. 注意我用前导空格使情况更一般。 The list comprehension is to remove the null strings at the front and back. 列表理解是删除前面和后面的空字符串。

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

This works even if ^\\s+ doesn't match: 即使^\\s+不匹配也可以:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

Here's why you need ^\\s+: 这就是您需要^ \\ s +的原因:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

See the leading spaces in blah? 看到等等的主要空间吗?

Clarification: above uses the Python 3 interpreter, but results are the same in Python 2. 说明:上面使用的是Python 3解释器,但结果与Python 2相同。


#3楼

I came to add: 我来补充:

map(str.strip, string.split(','))

but saw it had already been mentioned by Jason Orendorff in a comment . 但是看到Jason Orendorff在评论中已经提到了它。

Reading Glenn Maynard's comment in the same answer suggesting list comprehensions over map I started to wonder why. 在同一个答案中读到格伦·梅纳德(Glenn Maynard)的评论,这暗示了人们对地图的理解,我开始怀疑为什么。 I assumed he meant for performance reasons, but of course he might have meant for stylistic reasons, or something else (Glenn?). 我以为他是出于性能方面的考虑,但是当然他可能是出于风格方面的原因,或者其他原因(Glenn?)。

So a quick (possibly flawed?) test on my box applying the three methods in a loop revealed: 因此,在我的盒子上快速地(可能有缺陷?)应用了以下三种方法的测试:

[word.strip() for word in string.split(',')]
$ time ./list_comprehension.py
real    0m22.876smap(lambda s: s.strip(), string.split(','))
$ time ./map_with_lambda.py
real    0m25.736smap(str.strip, string.split(','))
$ time ./map_with_str.strip.py
real    0m19.428s

making map(str.strip, string.split(',')) the winner, although it seems they are all in the same ballpark. 使map(str.strip, string.split(','))成为赢家,尽管看起来他们都在同一个球场。

Certainly though map (with or without a lambda) should not necessarily be ruled out for performance reasons, and for me it is at least as clear as a list comprehension. 当然,出于性能原因,不一定要排除map(有或没有lambda),对我来说,它至少与列表理解一样清晰。

Edit: 编辑:

Python 2.6.5 on Ubuntu 10.04 Ubuntu 10.04上的Python 2.6.5


#4楼

s = 'bla, buu, jii'sp = []
sp = s.split(',')
for st in sp:print st

#5楼

re (as in regular expressions) allows splitting on multiple characters at once: re (如正则表达式中)允许一次拆分多个字符:

$ string = "blah, lots  ,  of ,  spaces, here "
$ re.split(', ',string)
['blah', 'lots  ', ' of ', ' spaces', 'here ']

This doesn't work well for your example string, but works nicely for a comma-space separated list. 这对于您的示例字符串而言效果不佳,但对于逗号分隔的列表则效果很好。 For your example string, you can combine the re.split power to split on regex patterns to get a "split-on-this-or-that" effect. 对于您的示例字符串,您可以结合使用re.split功能来分割正则表达式模式,以获得“此或该分割”效果。

$ re.split('[, ]',string)
['blah','','lots','','','','','of','','','','spaces','','here','']

Unfortunately, that's ugly, but a filter will do the trick: 不幸的是,这很丑陋,但是filter可以解决问题:

$ filter(None, re.split('[, ]',string))
['blah', 'lots', 'of', 'spaces', 'here']

Voila! 瞧!


#6楼

import re
result=[x for x in re.split(',| ',your_string) if x!='']

this works fine for me. 这对我来说很好。

用逗号分割并在Python中去除空格相关推荐

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

    用逗号分隔并在Python中删除空格 我有一些python代码分裂逗号,但不剥离空格: >>> string = "blah, lots , of , spaces, he ...

  2. chatgpt赋能python:Python中的空格:到底是重要的还是无关紧要的?

    Python中的空格:到底是重要的还是无关紧要的? 如果你正在使用Python编程语言,你很可能会遇到空格.但是,你是否了解Python编程中的空格到底有多重要?在本文中,我们将深入探讨Python中 ...

  3. jquery 逗号分割截取字符串_Python中常用的8种字符串操作方法

    一.拼接字符串 使用"+"可以对多个字符串进行拼接 语法格式: str1 + str2 >>> str1 = "aaa">>> ...

  4. python中去除字符串中首尾空格的函数_Python中去除字符串首尾特定字符的函数:strip()...

    Python中strip()函数的作用是去除一个字符串前导和尾部的特定字符,并返回结果字符串. Python中strip()函数默认是删除字符串前导和尾部空格,通过设定参数,也可以去除字符串前导和尾部 ...

  5. python中去除字符串中首尾空格的函数_Python字符串的首尾空格如何去掉?

    Python程序设计中,会用到很多字符串,字符串中可能包含空格.而空格看不见摸得着,因此空格可能会带来很多意想不到的错误,那么字符串的空格如何去掉? 今天我们就来学习,利用函数去掉字符串里的空格. 空 ...

  6. python中去除全角空格

    最近遇到一个需求是要清除中文字串中的全角空格(数据是GBK编码,全角空格的GBK编码是\xa1\xa1). 一开始直接使用str.replace(' ','')来去除,结果是部分结果出现乱码,经过分析 ...

  7. Python中去除字符串中空格的四种方法

    一.需求说明 业务需要对Pyhon中的一些字符串内容去除空格,方便后续处理. 二.思路分析 去除空格内容,可以使用去除字符串空格的函数或者直接使用替换函数即可. 三.实现方法 3.1.去除字符串头尾的 ...

  8. (二十九)、Java字符串中去除空格

    1.方法分类 str.trim(); //去掉首尾空格 str.replace(" ",""); //去除所有空格,包括首尾.中间 str.replaceAll ...

  9. python字符串去除空格,python去除字符串(string)空格的五种方法

    成年人的爱情不仅仅是简单的我爱你和漂亮的新衣服. python去掉字符串中的空格的方法总结 1.strip方法去掉字符串两边(开头和结尾)的空格 space_str = ' Remove the sp ...

最新文章

  1. drf认证组件源码分析
  2. 2016年,新的一年,新的元素。
  3. python返回unicode_我们如何从python中的字形id获取unicode?
  4. python数学计算_初学者Python学习笔记--数学计算
  5. vb初学回顾:最大公约数 最小公倍数 素数求取
  6. golang cover协程异常
  7. python 基础 7.1 datetime 获得时间
  8. android终端模拟器官方下载,Android 终端模拟器 | F-Droid - Free and Open Source Android App Repository...
  9. html 插入 flv,HTML中嵌入FLV视频文件
  10. 证件类型与证件号码前端验证
  11. 小区或公寓pppoe通过路由器怎么上网
  12. PHP 实现301转向代码
  13. 什么样的员工容易被提拔为管理者,他们有哪些共同特质?
  14. java 发卡平台支付_ZFAKA一款免费开源的发卡系统搭建教程 (支持多种支付接口)...
  15. Android--ImageView读取本地路径图片
  16. 苹果保修期_苹果手机怎么查看保修期 查询有效保修状态日期方法
  17. python写梦幻西游脚本精灵_python写的梦幻手游辅助工具,非外 挂
  18. java获取当前时间,时间戳,时间戳和时间相互转换
  19. 教你用PixiJs实现复杂动画
  20. 遇到vmware提示客户机操作系统已禁用 CPU.请关闭或重置虚拟机

热门文章

  1. UrlRewriter.NET 与 UrlRewrittingNet.UrlRewriter比较
  2. 基于BootStrap仿淘宝星星商品评价案例
  3. FET细解:FET(IGFET、JFET、MESFET)、IGFET(MOSFET/MISFET、HFET)、HFET(MODFET、HIGFET)
  4. 浏览器Goole Chrome调试工具
  5. window版加密磁盘
  6. Git连接GitHub仓库,同步上传图片及CSDN外链图片转存失败解决方案
  7. 通过internet连接到股票信息服务器,一种股票机的制作方法
  8. div默认外边距是多少_CSS外边距
  9. 高级测试にんじゃ修炼之道
  10. 埃森哲杯上海大学春季赛暨金马五校赛题解汇总