我有一个句子例如“你好,这是hello stackoverflow你好”。我需要做的是保持第一个你好,但删除句子中的其他“你好”。我该怎么做呢?
答案 0 :(得分:1)
parts = old.split("hello")
parts[1:1] = "hello"
new = "".join(parts)
似乎应该有更好的方式...
答案 1 :(得分:1)
必须比Ned更快,但价格是可读性:
>>> idx = s.find('hello') + len('hello')
>>> s[:idx] + s[idx:].replace('hello', '')
'hello this is stackoverflow '
答案 2 :(得分:1)
>>> s = 'hello this is hello stackoverflow hello'
>>> head, sep, tail = s.partition('hello')
>>> head + sep + tail.replace('hello', '')
'hello this is stackoverflow '
答案 3 :(得分:0)
非常糟糕的方式:
s = "hello this is hello stackoverflow hello"
s = s.replace("hello", "world").replace("world", "hello", 1)
它会将所有hello
替换为world
,然后仅将world
替换为hello
答案 4 :(得分:0)
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
答案 5 :(得分:0)
首先,每个人都会将此视为匹配模式的难题,所以问题是为什么hello
会重复?
如果假设第一个hello
,那么对字符串的简单过滤可以解决问题
s = 'hello this is hello stackoverflow hello'
l = s.split(' ')
"hello %s" % " ".join(filter (lambda a: a != 'hello', l))
'hello this is stackoverflow'
或者:
import re
s = 'hello this is hello stackoverflow hello'
re.sub('\shello\s?', ' ', s).strip()
'hello this is stackoverflow'