Python regex replace space from string if surrounded by numbers, but not letters
python, regex
Solution
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'
Problem
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