开发者

Python: Inverse Replace Function

I have no idea about how I explain this, but here goes...

>>> x = 'qwertyHello开发者_运维百科Worldasdfg'
>>> x = inversereplace(x, 'HelloWorld', 'a')
>>> print x  
aaaaaaHelloWorldaaaaaa  

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

In the function above, it replaces everything in x that is not Not the 2nd argument with the 3rd Argument.

How would I go about doing this?

If there is already a function that does this then please let me know.

Thanks in advance,

~DragonXDoom


This should work:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜