2011-01-13 100 views
1


我不知道我怎麼解釋這樣的想法,但在這裏不用...的Python:逆替換功能

>>> x = 'qwertyHelloWorldasdfg' 
>>> x = inversereplace(x, 'HelloWorld', 'a') 
>>> print x 
aaaaaaHelloWorldaaaaaa 

>>> y = 'qwertyHelloWorld' 
>>> y = inversereplace(y, 'qwerty', '') 
>>> print y 
qwerty 

在上面的功能,它取代了X的一切,是不是的與第三參數的第二個參數。
我該如何去做這件事?
如果已經有一個這樣做的功能,請讓我知道。

由於提前,
〜DragonXDoom

+0

你有一個實際使用情況的呢?我不能克服懷疑,必須有更好的方法... – simon 2011-01-13 04:24:45

回答

4

這應該工作:

def inversereplace(text, word, repl): 
    parts = text.split(word) 
    return word.join(repl*len(x) for x in parts) 
+0

噢,打我吧!另外,使用酷列表理解。一天一天,煲電話... – Malvolio 2011-01-13 04:27:46

+0

非常感謝你! – DragonXDoom 2011-01-13 05:01:25

1
def inversereplace(s, p, q): 
    s = s.split(p) 
    s = map(lambda x: q * len(x), s) 
    return p.join(s)