简体   繁体   中英

python re.sub : replace substring with string

In python,

with re.sub , how I can replace a substring with a new string ?

from

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

to

s = "hello number 20, Agosto 19"

I try

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

EDIT

the number 10 is a example, the number in the string can be any number.

You mean this?

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

OR

Using lookbehind,

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

Do not use regex for such simple cases. Normal string manipulation is enough (and fast):

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

If you don't know the number but know it is followed by a ,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM