Python replace()返回字符串的副本,其中出现的old已被new替换,可以选择将替换次数限制为max。
下面是Replace()方法-的语法
str.replace(old, new[, max])
old - 这是要替换的旧子字符串。
new - 这是新的子字符串,它将替换旧的子字符串。
max - 如果给定此可选参数max,则仅替换第一次计数。
此方法返回字符串的副本,其中所有出现的子字符串old替换为new。如果给定了可选参数max,则仅替换第一次出现的计数。
下面的示例显示replace()方法的用法。
#!/usr/bin/python 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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)