Home > Net >  regex to add space b/w alphabet and number
regex to add space b/w alphabet and number

Time:11-24

I have a string that has characters and numbers string is like

iPhone8s

i want the output to be iPhone 8s I have written this code

s = 'iPhone8s'
re.sub('(\d (\.\d )?)', r' \1 ', s).strip()

but it outputs iPhone 8 s how can i make the output to be iPhone 8s

i only want it for string that contains iPhone in it, i dont want to transform random8 as random 8

CodePudding user response:

i only want it for string that contains iPhone

then you have to put the iPhone into the regex

import re

s = 'iphone8s'
s = re.sub('iPhone(\d )', r'iPhone \1', s, 0, re.IGNORECASE)
print(s) # iPhone 8s

s = 'random8s'
s = re.sub('iPhone(\d )', r'iPhone \1', s, 0, re.IGNORECASE)
print(s) # random8s

CodePudding user response:

easy to understand and sort if you find for specifically for iphone word :

result='iphone8s'.lower().replace('iphone','iPhone ')
#iPhone 8s
  • Related