[英]how to replace specific word in a sentence with python
I have a sentence for example "hello this is hello stackoverflow hello". 我有一个句子,例如“你好,这是你好stackoverflow你好”。 What I need to do is keep the first hello but remove other "hello"s in the sentence. 我需要做的是保持第一个问候,但删除句子中的其他“ hello”。 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
它将用world
替换所有的hello
,然后用hello
只替换第一个world
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? 首先,每个人都将其视为匹配模式难题,所以问题是为什么hello
重复?
If the first hello
is assumed then a simple filtering of the string can fix the problem 如果假设第一次hello
,那么简单的字符串过滤就可以解决问题
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.