Skip to content Skip to sidebar Skip to footer

How To Search & Replace In Python?

How can I add a character '-' to a string such as 'ABC-D1234', so it becomes 'ABC-D-1234'? Also, how can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D1

Solution 1:

It depends on the rule you are using to decide where to insert the extra character.

If you want it between the 5th and 6th characters you could try this:

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

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

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

If you want it just before the first digit:

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

Can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34'

Sure:

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

or:

s = re.sub('(?<=\d\d)', '-', s, 1)

or:

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

Solution 2:

You could use slicing:

s = 'ABC-D1234's = s[0:5] + '-' + s[5:]

Solution 3:

Just for this string?

>>> 'ABC-D1234'.replace('D1', 'D-1')
'ABC-D-1234'

Solution 4:

If you're specifically looking for the letter D and the next character 1 (the other answers take care of the general case), you could replace it with D-1:

s = 'ABC-D1234'.replace('D1', 'D-1')

Post a Comment for "How To Search & Replace In Python?"