2011-01-13 99 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)