DGT
DGT

Reputation: 2654

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-D12-34' Many thanks.

Upvotes: 1

Views: 253

Answers (4)

Mark Byers
Mark Byers

Reputation: 838066

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('-') + 2
s = s[:i] + '-' + s[i:]

If you want it just before the first digit:

import re
i = 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)

Upvotes: 3

Blender
Blender

Reputation: 298106

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')

Upvotes: 0

miku
miku

Reputation: 188014

Just for this string?

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

Upvotes: 0

srgerg
srgerg

Reputation: 19329

You could use slicing:

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

Upvotes: 0

Related Questions