1

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.

1
  • Sorry for the confusion, guys. Commented Mar 16, 2011 at 22:51

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use slicing:

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

Comments

0

Just for this string?

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.