开发者

Python: Inverse Replace Function

开发者 https://www.devze.com 2023-02-04 03:46 出处:网络
I have no idea about how I explain this, but here goes... >>> x = \'qwertyHello开发者_运维百科Worldasdfg\'

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

精彩评论

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

关注公众号