Заменить 2-е вхождение строкового элемента в списке - PullRequest
0 голосов
/ 13 февраля 2020

Список ниже, и я хочу заменить 2-е вхождение 'pen' на 'his' в списке:

the_list = ['pen has pen cap', 'pen has pen ink', 'pen has pen attitude']

, ссылаясь на здесь :

def replace_second(string, a, b):
   return string.replace(a, b, 2).replace(b, a, 1)        # replace the 2nd occurrence 
   #return string.replace(b, a, 2).replace(a, b, 1)       # replace the 1st occurrence

new_list = [replace_second(t, 'pen', 'his') for t in the_list]

Вывод:

['pen has his cap', 'pen has his ink', 'pen has his attitude']

Что было бы лучше / быстрее? Спасибо.

И, вдохновленный @Keyur Potdar и @ AM C, другой способ может быть:

n = 2

for t in the_list:
    print (t.replace('pen','$$$',n-1).replace('pen','his',1).replace('$$$','pen'))

# pen has his cap
# pen has his ink
# pen has his attitude
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...