Python: Inverse Replace Function
>>> 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,
~DragonXDoomThis 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)
精彩评论