简体   繁体   中英

How to remove multiple spaces between numbers using a single re.sub

I would like to remove spaces between numbers using a single re.sub. With the following commands:

import re

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222")))

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33")))

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33 4")))

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33 4 55")))

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33 4 55 6")))

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33 4 55 6 77")))

I can however remove only spaces if there are more that one successive numbers:

11222
1122233
11222334
11222334 55
11222334 556
11222334 556 77

But how to remove also spaces with only one number, so that the result of command like

print(re.sub('([0-9,.]) ([0-9,.])','\\1\\2',str("11 222 33 4 55 6 77")))

would be

1122233455677

?

Try using lookarounds to detect the numbers surrounding a space:

print(re.sub('(?<=\\d) (?=\\d)','',str("11 222 33 4 55 6 77")))

1122233455677

The idea here is for each space we look behind and assert that a digit is present, and also we look ahead and assert that a digit is present.

Note that this answer won't remove spaces which might appear on either end of the string, but then again those spaces are not between numbers.

There are several expressions to grasp the digits. In this case, I find the simplest code in ref . It could get rid of other characters.

print(re.sub(r'\s','',str("11 222 33 4 55")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM