2011-12-27 11 views

答えて

1

ネッドの1よりも速いが、価格は読みやすさです。質問は、なぜhello繰り返しをしているので、

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

私はもともとforループでこのようなものを使っていました。 – incognito2

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

もっと良い方法があるはずのような非常に悪い方法

+0

:最初helloは、文字列の単純なフィルタリングが問題

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

かを修正することができますと仮定した場合

。 –

+0

問題はすべて「こんにちは」が同じ大文字ではない可能性があります。こんにちはのいずれかの大文字と異なる場合、それは正しく動作しません。 – incognito2

+1

@ incognito2公平ではない!大文字の問題は、元の質問を完全に変更します。 – ekhumoro

0

...ようだ:

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

それはhelloによってのみ最初worldを交換、その後、worldによってすべてhelloを交換します

+0

あなたの入力文字列がすでに "hello"の前に "world"を含んでいるまで、素晴らしい動作をします。 – kindall

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

はまず、誰もが一致パターンの難問としてこれを見るのだろうか?このいずれかで多分問題の間隔、FYI

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

最初の 'hello'が文字列の先頭にある場合にのみ動作します。 – ekhumoro

+0

正確に私が言ったことを言った理由は、この問題をパターンの問題と見なすので、私たちはそのように修正しようとしますが、このインスタンスではなぜこんにちはが繰り返されますか? –

+0

彼らは誰でも入力したランダムな文章です – incognito2

関連する問題