我有一个字符串,我想在每次第二次出现后替换the
。
s = "change the string in the sentence and the save"
我希望将the
替换为hello
。但除了第一个。
输出应为:
change the string in hello sentence and hello save
答案 0 :(得分:3)
我会将右边的字符串与您要替换使用str.rsplit()
函数的单词分开,但只会分割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'
答案 1 :(得分:1)
试试这个:
def replace_not_first(str, word, replace):
str_arr = str.split(word)
return str_arr[0] + word + replace.join(str_arr[1:])
str = "change the string in the sentence and the save"
print(replace_not_first(str, 'the', 'hello'))
打印:change the string in hello sentence and hello save
答案 2 :(得分:1)
这应该有效
string = "change the string in the sentence and the save"
the_arr = string.split("the")
print the_arr[0] + "the" + "hello".join(the_arr[1:])`
答案 3 :(得分:1)
尝试以下一种衬垫解决方案。
string = 'change the string in the sentence and the save'
new_string = string[:string.find('the')+3] + string[string.find('the')+3:].replace('the', 'hello')
答案 4 :(得分:1)
我希望这能做到这一点。
str = str.partition('the')[0] + str.partition('the')[1] + str.partition('the')[-1].replace('the','hello')
答案 5 :(得分:1)
>>> str = "change the string in the sentence and the save"
>>> str.replace('the', 'hello')
>>> str.replace('hello', 'the',1)
答案 6 :(得分:1)
试试这个:
>>> s = "change the string in the sentence and the save"
>>> s.split("the",1)[0]+"the" + s.split("the",1)[1].replace("the","hello")
'change the string in hello sentence and hello save'
答案 7 :(得分:0)
您可以将字符串拆分为多个部分:
string = "change the string in the sentence and the save"
splitString = string.split()
firstIndex = splitString.index('the')
part1 = ' '.join(splitString[:firstIndex+1])
part2 = ' '.join(splitString[firstIndex+1:]).replace('the','hello')
newString = part1 + ' ' + part2
或者在一行中:
newString = ' '.join(['hello' if j == 'the' and i != string.split().index('the') else j for i, j in enumerate(string.split())])