Skip to main content
 首页 » 编程设计

python之字符串替换而不替换第一个实例

2025年05月04日20小虾米

我有一个字符串,我只想在它第二次出现后每次替换 the。

s = "change the string in the sentence and the save" 

我想将单词 the 替换为 hello。但第一个除外。

输出应该是:

change the string in hello sentence and hello save 

请您参考如下方法:

我会用你要替换的词从右边拆分字符串使用 str.rsplit()功能,但只 split s.count('the') - 1次。

然后,用hello加入输出列表:

>>> s.rsplit('the', s.count('the') - 1) 
['change the string in ', ' sentence and ', ' save'] 
 
>>> 'hello'.join(s.rsplit('the', s.count('the') - 1)) 
'change the string in hello sentence and hello save'