[英]python re.sub : replace substring with string
在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
是示例,字符串中的數字可以是任何數字。
你是這個意思?
>>> 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'
對於此類簡單情況,請勿使用正則表達式。 普通的字符串操作就足夠了(並且很快):
s = "hello number 10, Agosto 19"
s = s.replace('10', '20')
如果您不知道數字,但知道其后是,
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.