我有一个字符串,我只想在它第二次出现后每次替换 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'
