📜  Python中的 replace() 替换子字符串

📅  最后修改于: 2022-05-13 01:55:46.573000             🧑  作者: Mango

Python中的 replace() 替换子字符串

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

例子:

Input  : str = "helloABworld"
Output : str = "helloCworld"

Input  : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"

此问题已有解决方案,请参阅将所有出现的字符串AB 替换为 C 而无需使用额外空间链接。我们使用字符串数据类型的replace()方法在Python中快速解决了这个问题。

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

# Function to replace all occurrences of AB with C
  
def replaceABwithC(input, pattern, replaceWith):
    return input.replace(pattern, replaceWith)
  
# Driver program
if __name__ == "__main__":
    input   = 'helloABworld'
    pattern = 'AB'
    replaceWith = 'C'
    print (replaceABwithC(input,pattern,replaceWith))

输出:

'helloCworld'