【问题标题】:How can I replace the second occurrence in a string?如何替换字符串中的第二次出现?
【发布时间】:2020-07-10 02:51:37
【问题描述】:

我想将“It's raining cat and cats”中第二次出现的“cats”替换为“dogs”。

text = "Its raining cats and cats"
a = text.replace(str(text.endswith("cats")), "dogs")
print(a)

【问题讨论】:

  • 问题很好,如何替换子串的第二个精度。
  • 您共享的答案略有不同,它只替换了一个在字符串中也只出现一次的单词。
  • 如果有更清洁的方法,我不会这样做,但这里是:index = text.find('cats', text.find('cats') + 1)a = text[:index] + 'dogs' + text[index + 4:] # 4 is 'dogs' length
  • 顺便说一句,有很多方法可以实现这一点。我认为我的建议不值得使用,您也可以使用 split 和 join 来完成。
  • 第n次使用这个text.replace('cats', '%s') % (('cats',) * (n - 1) + ('dogs',))

标签: python replace


【解决方案1】:

首先查找第一个匹配项,然后在该点之后替换。还要为str.replace 设置一个计数,以确保只替换第二个匹配项。

text = "It's raining cats and cats"
old, new = 'cats', 'dogs'
offset = text.index(old) + 1
a = text[:offset] + text[offset:].replace(old, new, 1)
print(a)  # -> "It's raining cats and dogs"

附:我还把它变成了一个超级通用的库函数,稍后我可能会在 GitHub 上发布。我猜,请按照此答案进行更新。

【讨论】:

  • P.p.s.抱歉,ShayThan,我本来想回复的,但我想我忘记了,或者看到 cmets 并认为 Hagai Wild 会写一个。
【解决方案2】:
def replace_ending(sentence, old, new):
    sentence_array = sentence.split()
    if sentence_array[-1]== old:
        sentence  = sentence.rsplit(" ",1)[0];
        new_sentence = sentence + " " + new
        return new_sentence
    return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs"))

【讨论】:

    【解决方案3】:

    试试这个:

    text = "Its raining cats and cats".split(' ') # splits it at space
    text[text.index('cats', text.index('cats')+1)] = 'dogs' # find where cat occurs after the first occurrence (if you have 3 instead of two and want to replace the third, this won't work) and replaces it
    text = " ".join(text) # rejoins text using space
    

    【讨论】:

      猜你喜欢
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      相关资源
      最近更新 更多