【问题标题】:How to replace the second "is" from the sentence using replace method如何使用替换方法替换句子中的第二个“是”
【发布时间】:2018-09-30 16:23:08
【问题描述】:
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)

【问题讨论】:

标签: python


【解决方案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

【讨论】:

    【解决方案2】:

    您可以.split() 字符串然后使用enumerate 创建包含单词isitems 的索引列表。然后您可以获取该列表中的第二个索引并使用该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))
    
    My name is David and I live in India
    

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2018-12-19
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多