I want to separate string from the digits using regex. I don't want to replace anything just add space. I don't want to add space in digit and special character or string and special character. for example
"A-21PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK VIHAR110052"
output for above example should look like,
"A-21 PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK VIHAR 110052"
in this example I want to add space between alphabets and number. there are number attached with '-' or any special character , I don't want to do anything with it.
CodePudding user response:
User re.sub:
thestring = re.sub(r'(\d)([A-Z])', r'\1 \2', thestring)
thestring = re.sub(r'([A-Z])(\d)', r'\1 \2', thestring)
First one puts spaces between digits and capital letters, second one between capital letters and digits.
CodePudding user response:
One pass by positive lookahead assertion (?<=...)
.
import re
istr = "A-21PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK VIHAR110052"
ostr = re.sub(r'(?<=[a-zA-Z])(\d)|(?<=\d)([a-zA-Z])', r' \1\2', istr)
print(ostr)
# A-21 PHASE-1,ASHOK VIHARA-21, PHASE-1, - ASHOK VIHAR 110052
istr = 'a1B2c3 1A2b3C'
ostr = re.sub(r'(?<=[a-zA-Z])(\d)|(?<=\d)([a-zA-Z])', r' \1\2', istr)
print(ostr)
# a 1 B 2 c 3 1 A 2 b 3 C