在Python中,用于替换字符串的函数主要是`replace()`函数。以下是`replace()`函数的基本用法:
```python
new_string = old_string.replace(old_substring, new_substring, max_replacements)
其中:`old_string` 是原始字符串。`old_substring` 是需要被替换的子串。`new_substring` 是替换后的子串。`max_replacements` 是一个可选参数,指定替换操作的最大次数。如果不指定,则替换所有匹配的子串。`replace()`函数会返回一个新的字符串,原始字符串不会被修改。例如:```pythontext = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) 输出:Hello, Python!
如果你需要更复杂的替换,例如使用正则表达式进行替换,可以使用`re.sub()`函数:
```python
import re
new_string = re.sub(pattern, new_substring, old_string)
其中`pattern`是一个正则表达式,用于匹配需要被替换的子串。

