`replace` 是 Python 中字符串对象的一个内置方法,用于替换字符串中的特定子串。其基本语法如下:
str.replace(old, new[, count])
其中:
`str` 是要进行替换操作的字符串。
`old` 是要被替换的子字符串。
`new` 是用于替换 `old` 的新子字符串。
`count` 是一个可选参数,表示替换的次数,如果不指定,则默认替换所有匹配的子串。
`replace` 方法返回一个新的字符串,原始字符串不会被改变。
例如,如果你有一个字符串 `"Hello, World!"`,并且想要将所有的逗号替换为感叹号,你可以这样做:
text = "Hello, World!"
cleaned_text = text.replace(",", "!")
print(cleaned_text) 输出 "Hello! World!"
如果你想要限制替换的次数,比如只替换前两个逗号,你可以这样写:
text = "Hello, World!"
cleaned_text = text.replace(",", "!", 2)
print(cleaned_text) 输出 "Hello! World!"
需要注意的是,`replace` 方法对大小写是敏感的