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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With