簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM