How to search & replace in Python? -


How can I add a character to a string such as "ABC-D1234", so it's 'ABC-D1234'? Apart from this, how can I add a character after 'ABC-D1234' to 'ABC-D12-34' before 2 numbers? thanks a lot.

It depends on the rule that you are using to decide to enter extra characters .

If you want it between 5th and 6th characters then you can try it:

  s = s [: 5] + '-' + S [5:]   

If you want it after the hyphen first and then another character:

  i = s.index ('-' ) + 2 s = s [: i] + '-' + s [i:]   

If you want it before the first digits:

  Import re i = re.search ('\ d', s) .start () s = s [: i] + '-' s [i:]   

Can I add an aerobic after the first 2 numbers, i.e. 'ABC-D1234' to 'ABC-D12-34' '

Sure:

  i = re-search ('(? & Lt; = \ d \ d)', s) .start () s = S [: i] + '-' + [I:]   

or:

  s = re.sub ('(? & Lt; = \ D \ d)', '-' , S, 1)   

or:

  s = re.sub ('(\ d \ d)', r '\ 1-', S, 1)    

Comments