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.
4 Answers
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)