Python ProgrammingPython Programming

Python regex add space whenever a number is adjacent to a non-number

import re

text = ['123', 'abc', '4x5x6', '7.2volt', '60BTU',
        '20v', '4*5', '24in', 'google.com-1.2', '1.2.3']

pattern = r'(-?[0-9]+\.?[0-9]*)'
for data in text:
    print(repr(data), repr(
        ' '.join(segment for segment in re.split(pattern, data) if segment)))
Output
'123' '123'
'abc' 'abc'
'4x5x6' '4 x 5 x 6'
'7.2volt' '7.2 volt'
'60BTU' '60 BTU'
'20v' '20 v'
'4*5' '4 * 5'
'24in' '24 in'
'google.com-1.2' 'google.com -1.2'
'1.2.3' '1.2 . 3'