我有一个字符串,每次只在第二次出现之后都要替换the
。
s = "change the string in the sentence and the save"
我想把the
这个词替换为hello
。但除了第一个。
产出应是:
change the string in hello sentence and hello save
发布于 2016-06-09 02:00:12
试试这个:
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
发布于 2016-06-09 02:09:09
我会用要替换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'
发布于 2016-06-09 02:01:20
这应该能行
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:])`
https://stackoverflow.com/questions/37722539
复制