`replace` 在 Python 中是一个字符串替换方法,用于将字符串中的某个子字符串替换为另一个子字符串。其基本语法如下:
string.replace(old, new, count)
其中:
`string` 是要进行替换操作的原始字符串。
`old` 是需要被替换的子字符串。
`new` 是用来替换 `old` 的新子字符串。
`count` 是一个可选参数,表示替换操作的次数,如果不指定,则默认替换所有匹配的子字符串。
`replace` 方法返回一个新的字符串,原始字符串不会被改变。
例如:
text = "This is a text with extra spaces."
cleaned_text = text.replace("extra", "many")
print(cleaned_text) 输出:"This is a text with many spaces."
在这个例子中,`text` 字符串中的 "extra" 被替换为 "many"