python re.sub:用字符串替换子串

0 投票
3 回答
22201 浏览
提问于 2025-04-18 17:48

在Python中,

使用 re.sub,我该如何把一个子字符串替换成一个新字符串呢?

number = "20"
s = "hello number 10, Agosto 19"

s = "hello number 20, Agosto 19"

我试过

re.sub(r'number ([0-9]*)', number, s)

编辑

这里的数字 10 只是个例子,字符串中的数字可以是任何数字。

3 个回答

2

对于这么简单的情况,不要使用正则表达式。普通的字符串处理就足够了(而且速度很快):

s = "hello number 10, Agosto 19"
s = s.replace('10', '20')
2

如果你不知道这个数字是什么,但你知道它后面跟着一个,(逗号)

import re
re.sub("\d+(?=,)","20",s) # one or more digits followed by a ,
hello number 20, Agosto 19

import re
re.sub("(\d+)","20",s,1) # first occurrence
hello number 20, Agosto 19
6

你是说这个吗?

>>> import re
>>> m = re.sub(r'10', r'20', "hello number 10, Agosto 19")
>>> m
'hello number 20, Agosto 19'

或者

使用反向查找,

>>> number = "20"
>>> number
'20'
>>> m = re.sub(r'(?<=number )\d+', number, "hello number 10, Agosto 19")
>>> m
'hello number 20, Agosto 19'

撰写回答