Python3 string.replace()方法

replace()方法返回使用 new 来替换所有出现的 old,可选择更换限制到最大数目的字符串的副本。

语法

以下是 replace()方法的语法 -
str.replace(old, new[, max])

参数

  • old -- 这是要替换旧字符串

  • new -- 这是新的字符串,这将用于取代旧的子字符串。

  • max -- 如果给定可选参数max,只有第一个匹配项被取代

返回值

此方法返回所有出现被新的取代旧的子串的字符串副本。如果可选参数max给定,只有第一个匹配项取代。

示例

下面的示例显示 replace()方法的使用说明。
#!/usr/bin/python3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

当我们运行上面的程序,会产生以下结果 -
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

上一篇: Python3数字 下一篇: Python3字符串