📜  Python中的replace替换子字符串

📅  最后修改于: 2020-07-13 10:20:35             🧑  作者: Mango

给定一个字符串str,其中可能包含一个或多个“ AB”。将str中所有出现的“ AB”替换为“ C”。

例子:

输入:str =“ helloABworld"
输出:str =“ helloCworld"

输入:str =“ fghABsdfABysu"
输出:str =“ fghCsdfCysu

replace()函数如何工作?
str.replace(pattern,replaceWith,maxCount)至少接受两个参数,并用指定的子字符串replaceWith替换所有出现的模式。第三个参数maxCount是可选的,如果我们不传递此参数,则replace函数将对所有出现的模式进行处理,否则,它将仅替换maxCount次出现的模式。 

# 用C代替所有出现的AB的功能
  
def replaceABwithC(input, pattern, replaceWith): 
    return input.replace(pattern, replaceWith) 
  
# 驱动程式 
if __name__ == "__main__": 
    input   = 'helloABworld'
    pattern = 'AB'
    replaceWith = 'C'
    print replaceABwithC(input,pattern,replaceWith) 

输出: 

'helloCworld'