字符串中替换指定字符串
时间: 2023-07-06 22:11:29 浏览: 42
在 Python 中,可以使用 replace 方法来替换字符串中的指定子字符串。replace 方法接受两个参数,第一个参数是要替换的子字符串,第二个参数是替换后的字符串。例如:
```python
my_string = "hello world"
new_string = my_string.replace("hello", "hi")
print(new_string) # 输出:hi world
```
在这个例子中,我们用 replace 方法将字符串中的 "hello" 替换成了 "hi"。
如果想替换字符串中所有匹配的子字符串,可以使用 replace 方法的第三个参数 count。例如:
```python
my_string = "hello world"
new_string = my_string.replace("l", "z", 2)
print(new_string) # 输出:hezzo world
```
在这个例子中,我们用 replace 方法将字符串中的前两个 "l" 替换成了 "z"。
还有一种更灵活的方法是使用正则表达式来替换字符串中的指定子字符串,可以使用 re 模块来实现。例如:
```python
import re
my_string = "hello world"
new_string = re.sub(r"l+", "z", my_string)
print(new_string) # 输出:hezzo worzd
```
在这个例子中,我们使用 re.sub 函数将字符串中的所有连续的 "l" 替换成了 "z"。