Python String replace() 方法将字符串中一个子字符串的所有匹配项替换为另一个子字符串。此方法用于通过替换原始字符串的某些部分来创建另一个字符串,其 gist 可能保持不变。
例如,在实时应用程序中,此方法可用于一次替换文档中的多个相同拼写错误。
此 replace() 方法还可以替换字符串中出现的选定数量的子字符串,而不是替换所有子字符串。
语法
以下是 Python String replace() 方法的语法 -
str.replace(old, new[, count])
参数
- old − 这是要替换的旧子字符串。
- new − 这是 new substring,它将替换 old substring。
- count − 如果给出了此可选参数 count,则仅替换第一个 count 出现次数。
返回值
此方法返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 count ,则仅替换第一个 count 出现次数。
例以下示例显示了 Python String replace() 方法的用法。
str = "Welcome to qikepucom"
str_replace = str.replace("o", "0")
print("String after replacing: " + str_replace)
当我们运行上述程序时,它会产生以下结果——
String after replacing: Welc0me t0 qikepuc0m
例
当我们传递 substring 参数和可选的 count 参数时,该方法仅替换字符串中的第一个 count 出现次数。
在下面的示例中,将创建输入字符串,该方法采用三个参数:两个子字符串和一个 count 值。返回值将是替换第一个 count 出现次数后获得的字符串。
str = "Fred fed Ted bread and Ted fed Fred bread."
strreplace = str.replace("Ted", "xx", 1)
print("String after replacing: " + strreplace)
当我们运行上述程序时,它会产生以下结果——
String after replacing: Fred fed xx bread and Ted fed Fred bread.
例
当我们向方法传递两个子字符串并且 count = 0 作为参数时,原始字符串将作为结果返回。
在以下示例中,我们创建了一个字符串 “Learn Python from qikepu” ,并尝试使用 replace() 方法将单词 “Python” 替换为 “Java”。但是,由于我们将计数传递为 0,因此此方法不会修改当前字符串,而是返回原始值(“Learn Python from qikepu”)。
str = "Learn Python from qikepu"
strreplace = str.replace("Python", "Java", 0)
print("String after replacing: " + strreplace)
如果执行上述程序,则出海坑将显示为 -
String after replacing: Learn Python from qikepu