I am trying to split and then join the first alphanumeric occurrence by space and keep other occurrences as it is, but not getting the pattern to do that. For ex: string: Johnson12 is at club39 converted_string: Jhonson 12 is at club39
Desired Output:
input = "Brijesh Tiwari810663 A14082014RGUBWA"
output = Brijesh Tiwari 810663 A14082014RGUBWA
Code:
import re
regex = re.compile("[0-9]{1,}")
testString = "Brijesh Tiwari810663 A14082014RGUBWA" # fill this in
a = re.split('([^a-zA-Z0-9])', testString)
print(a)
>> ['Brijesh', ' ', 'Tiwari810663', ' ', 'A14082014RGUBWA']
CodePudding user response:
Here is one way. We can use re.findall
on the pattern [A-Za-z] |[0-9]
, which will alternatively find all letter or all number words. Then, join that resulting list by space to get your output
inp = "Brijesh Tiwari810663 A14082014RGUBWA"
output = ' '.join(re.findall(r'[A-Za-z] |[0-9] ', inp))
print(output) # Brijesh Tiwari 810663 A 14082014 RGUBWA
Edit: For your updated requirement, use re.sub
with just one replacement:
inp = "Johnson12 is at club39"
output = re.sub(r'\b([A-Za-z] )([0-9] )\b', r'\1 \2', inp, 1)
print(output) # Johnson 12 is at club39