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

时间:2015-03-10 11:21:17

标签: 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","oware")

我希望这与out replace方法一起使用。我怎么能这样做(使用Python)???

1 个答案:

答案 0 :(得分:0)

使用RegExp,查看ideOne

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")