incognito2 incognito2 - 1 day ago 5
Python Question

how to replace specific word in a sentence with python

I have a sentence for example "hello this is hello stackoverflow hello". What I need to do is keep the first hello but remove other "hello"s in the sentence. How would I go about doing this?

Answer

Must be faster than Ned's one, but the price is readability:

>>> idx = s.find('hello') + len('hello')
>>> s[:idx] + s[idx:].replace('hello', '')
'hello this is  stackoverflow '
Comments