简体   繁体   中英

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?

parts = old.split("hello")
parts[1:1] = "hello"
new = "".join(parts)

Seems like there should be a better way...

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 '
>>> s = 'hello this is hello stackoverflow hello'
>>> head, sep, tail = s.partition('hello')
>>> head + sep + tail.replace('hello', '')
'hello this is  stackoverflow '

Very bad way:

s = "hello this is hello stackoverflow hello"
s = s.replace("hello", "world").replace("world", "hello", 1)

It will replace all the hello by world , then replace only the first world by hello

s = "hello this is hello stackoverflow hello"
t = "hello"

i = s.index(t) + len(t) + 1
s = s[:i] + s[i:].replace(t, "")

print s # hello this is  stackoverflow 

Firstly, everyone will see this as a matching pattern conundrum, so the question is why does hello repeat?

If the first hello is assumed then a simple filtering of the string can fix the problem

s = 'hello this is hello stackoverflow hello'
l = s.split(' ')
"hello %s" % " ".join(filter (lambda a: a != 'hello', l))
'hello this is stackoverflow'

Or:

import re
s = 'hello this is hello stackoverflow hello'
re.sub('\shello\s?', ' ', s).strip()
'hello this is stackoverflow'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM