re.sub 用逗号替换空格 [英] re.sub replace spaces with comma

查看:44
本文介绍了re.sub 用逗号替换空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的项目列表:

 2.4 -2.0 4.3-6.0 12.5 1.0

我想要的是删除所有这些空格并用,"(逗号)替换它们,除了第一个数字前面的空格(它们应该被删除(空格)而不是任何替换).所以上面的字符串项目应该是这样的,替换后:

2.4,-2.0,4.3-6.0,12.5,1.0

不是这样:

,2.4,-2.0,4.3,-6.0,12.5,1.0

以下代码的作用:

newStrings = []对于字符串中的 s:newStrings.append(re.sub('\s+', ',', s))

应该使用 re.sub 的什么正则表达式来实现这一点?谢谢.

解决方案

要删除前导和尾随空格可以使用 .strip(),然后使用正则表达式替换连续的空格字符\s+:

<预><代码>>>>进口重新>>>s = " 2.4 -2.0 4.3">>>re.sub("\s+", ",", s.strip())'2.4,-2.0,4.3'

I have a list of items which look like so:

 2.4       -2.0           4.3
-6.0       12.5           1.0

What I would like is to remove all those spaces and replace them with "," (comma) except for the spaces in front of first numbers (they should be just deleted (the spaces) and not replaced with anything). So the upper string items should look like so, after replacement:

2.4,-2.0,4.3
-6.0,12.5,1.0

Not like this:

,2.4,-2.0,4.3
,-6.0,12.5,1.0

Which is what the following code does:

newStrings = []
for s in strings:
    newStrings.append(re.sub('\s+', ',', s))

What regular expression for re.sub should be used to achieve that? Thank you.

解决方案

To remove the leading and trailing spaces you can use .strip(), and then to replace consecutive whitespace characters using the regular expression \s+:

>>> import re
>>> s = " 2.4       -2.0           4.3"
>>> re.sub("\s+", ",", s.strip())
'2.4,-2.0,4.3'

这篇关于re.sub 用逗号替换空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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