replace用法

admin 39 0

`replace()` 是一个常见的字符串方法,用于在 Python 中替换字符串中的某些字符或子串,以下是 `replace()` 方法的基本用法:

string.replace(old, new[, count])

参数说明:

* `old`:需要被替换的子串。

* `new`:替换后的新子串。

* `count`(可选):替换操作的次数,如果指定了该参数,则只会替换前 `count` 次出现的 `old` 子串,如果不指定该参数,则所有出现的 `old` 子串都会被替换。

text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text)  # 输出:Hello, Python!

在上面的示例中,我们将字符串 "Hello, world!" 中的 "world" 替换为 "Python"。

如果要替换的子串在字符串中出现了多次,并且只想替换其中的一部分,可以使用 `count` 参数:

text = "apple apple apple"
new_text = text.replace("apple", "orange", 2)
print(new_text)  # 输出:orange orange apple

在上面的示例中,我们将字符串 "apple apple apple" 中的前两个 "apple" 替换为 "orange",第三个 "apple" 没有被替换。