Как я могу заменить второе вхождение в строке? - PullRequest
1 голос
/ 29 марта 2020

Я хочу заменить второе вхождение «кошки» в «Идет дождь кошек и кошек» на «собаки».

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

Ответы [ 3 ]

0 голосов
/ 26 апреля 2020

Попробуйте это:

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
0 голосов
/ 27 апреля 2020

Начните с поиска первого вхождения, затем замените после этого момента. Также установите count для 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"

Ps Я также превратил это в супер-универсальную библиотечную функцию, которую я, вероятно, буду publi sh на GitHub позже. Следуйте этому ответу для обновления, я думаю.

0 голосов
/ 26 апреля 2020
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"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...