Python re.sub 用逗号替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26949752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:13:26  来源:igfitidea点击:

re.sub replace spaces with comma

pythonregexstringreplace

提问by marco

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.

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

采纳答案by DanielGibbs

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

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

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

回答by internety

There are many solutions... This doesn't even briefly cover the whole topic, but it works:

有很多解决方案......这甚至没有简要涵盖整个主题,但它有效:

Quick solution:

快速解决方案

In [1]: import re
   ...: d_in = "strip \t\r\n\x00er \ter\rMY\   nr\x00 \t\r\nSPAC       ES\x00  ! "
   ...: d_out = re.sub("\s+", r",", d_in)
   ...: d_out
   ...: 
Out[1]: 'strip,\x00er,er,MY\,nr\x00,SPAC,ES\x00,!,'