使用python中的regex将字符串中的第一个数字更改为"#"

Awe*_*irl 3 python regex string

import re    
sentence = "the cat is called 303worldDomination"    
print re.sub(r'\d', r'#', sentence)
Run Code Online (Sandbox Code Playgroud)

但是,这会用'#'替换字符串中的所有数字

我只希望字符串中的第一个数字被'#'替换

Ale*_*ley 11

您可以使用该count参数指定只应进行一次替换(即第一次匹配):

>>> re.sub(r'\d', r'#', sentence, count=1)
'the cat is called #03worldDomination'
Run Code Online (Sandbox Code Playgroud)