python 字符串替换



在Python中,你可以使用str.replace()方法来替换字符串中的特定部分。这个方法的基本语法是:

new_string = original_string.replace(old, new[, count])

这里:

  • old:需要被替换的子字符串。
  • new:用来替换old子字符串的新子字符串。
  • count(可选):替换操作的次数。如果指定了这个参数,那么替换只会进行最多count次。

下面是一个简单的例子:

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

在这个例子中,"world"被替换成了"Python"。

如果你想要限制替换的次数,你可以使用count参数。例如:

original_string = "apple apple apple"  
new_string = original_string.replace("apple", "orange", 2)  
print(new_string)  # 输出:orange orange apple

在这个例子中,我们将"apple"替换为"orange",但由于指定了count为2,所以只有前两个"apple"被替换了