Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex: Put the space between digit and character

I have the following simple string:

a = "total net band width 13.5mm. 12.25mm 13.5mm 5mm 11.5mm speed"

How do I insert a space between 2 consecutive characters if one the first is a digit and the second is an alphabet?

Here is what I have tried so far using python regex:

    re.sub('\d+\.\d+', " ", a)

Desired output:

"total net band width 13.5 mm. 12.25 mm 13.5 mm 5 mm 11.5 mm speed"
like image 487
TRINADH NAGUBADI Avatar asked Apr 24 '26 03:04

TRINADH NAGUBADI


1 Answers

Create a capturing group, using ( and ).

Then put the contents of that group in the output, using \1:

re.sub(r'(\d+\.\d+)', r'\1 ', a)

Of course, that fails on 5mm since there is no decimal component. Better to use a character class:

re.sub(r'(\d[\.\d]*)', r'\1 ', a)

If you want to be pendantic about rejecting inputs like 5..6 then some ? qualifiers would be suitable.

like image 196
J_H Avatar answered Apr 25 '26 20:04

J_H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!