开发者

How to search & replace in Python?

How can I add a character "-"开发者_如何学C 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.


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)


You could use slicing:

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


Just for this string?

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜