Python:反向替换函数

标签 python replace


我不知道我该如何解释这一点,但这里是......

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

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

在上面的函数中,它用第三个参数替换了 x 中不是不是第二个参数的所有内容。
我该怎么做呢?
如果已经有执行此操作的函数,请告诉我。

提前致谢,
~DragonXDoom

最佳答案

这应该有效:

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

关于Python:反向替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4676700/

相关文章:

python - 在没有终端的情况下打开 kivy 小部件?

c++ - 在 C++ 中使用 Python 3.3 'python33_d.lib' 未找到

python - 替换 pandas 数据框行会覆盖所有列的 dtypes

regex - 在文件中每行的开头和结尾添加字符

c# - 替换/删除与正则表达式 (.NET) 不匹配的字符

.net - 您如何在ReSharper 5中使用模式匹配功能?

python - 如何用 pandas 完成一些缺失日期的时间序列数据

python - Objective-C 中非常慢的两个和解决方案的变体

python - 使用另一个数据框更新值

mysql - Informix 相当于 MySQL 'Replace' 命令