如何使用替换方法替换句子中的第二个“是”

时间:2018-09-30 16:23:08

标签: python

strring ="My name is David and I live is India" # correct the grammer using find and replace method
new_str=strring.find("is")  # find the index of first "is"
print(new_str)
fnl_str=strring.replace("is","in")  # replace "is" with "in" ( My name is David and I live in India )
print(fnl_str)

2 个答案:

答案 0 :(得分:1)

也许str.rpartition()在这里解决了这种情况,尽管不是一般解决方案:

strring = "My name is David and I live is India"

first, sep, last = strring.rpartition('is')
print(first + 'in' + last)
# My name is David and I live in India

答案 1 :(得分:0)

您可以.split()字符串,然后使用enumerate创建包含单词items的{​​{1}}索引列表。然后,您可以获取该列表中的第二个索引,并使用该is将该项目更改为index。然后使用in将其放回原处

' '.join()
s = "My name is David and I live is India"
s = s.split()
loc = []
for idx, item in enumerate(s):
    if item == 'is':
        loc.append(idx)

s[loc[1]] = 'in'

print(' '.join(s))