Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex replace space from string if surrounded by numbers, but not letters

Tags:

python

regex

My input variants as strings:

'12345 67890'
'abc 123'
'123 abc'
'abc def'

My aim is to remove the space if found between the characters if characters from both sides are digits, but not letters. I was considering using the re module, perhaps re.sub() function, or something similar.

Desired output:

'1234567890'
'abc 123'
'123 abc'
'abc def'

Thank you

like image 669
Sazzy Avatar asked Dec 11 '25 09:12

Sazzy


1 Answers

Using regex with lookahead and lookbehind:

>>> import re
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '12345 67890')
'1234567890'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc 123')
'abc 123'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc')
'123 abc'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc def')
'abc def'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc 1234 456')
'123 abc 1234456'
like image 127
Ashwini Chaudhary Avatar answered Dec 13 '25 22:12

Ashwini Chaudhary