Python替换字符串中某些字符的替代方法

Python替换字符串中某些字符的替代方法,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有“hihwru”,我想用“oware”替换“wr”,而不使用Python中的replace方法 下面是我的代码: def Rep(str,chr,Rchr): if chr in str: str1=str.replace(chr,Rchr) print(str1) else: print("character is not present in the string to replace") Rep("Hihwru","wr

我有“hihwru”,我想用“oware”替换“wr”,而不使用Python中的replace方法

下面是我的代码:

def Rep(str,chr,Rchr):
    if chr in str:
        str1=str.replace(chr,Rchr)
        print(str1)
    else:
        print("character is not present in the string to replace")

Rep("Hihwru","wr","oware")
我想用out-replace方法。我如何(使用Python)实现它???

使用RegExp,查看


您可以将字符串转换为列表,替换列表中的一个片段,然后将其重新连接到字符串。或者使用
re.sub
。但是为什么呢?你只是想避免那个特殊的方法,还是这是一个用来编写你自己的替换方法的任务?是的,伙计,这是我的任务工作…@tobias_kWell,如果这是一个用来编写你自己的替换方法的任务,那么仅仅使用
re.sub
而不是
str.replace
可能不会给你太多的信任。。。
import re

def Rep(str,chr,Rchr):
    if chr in str:
        str1 = Rchr if chr else None
        result = re.sub(chr, str1, str)
        print(result)
    else:
        print("character is not present in the string to replace")

Rep("Hihwru","wr","oware")