incognito2 incognito2 - 1 year ago 93
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 Source

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 '
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download