python,replace用法
时间: 2023-12-26 22:27:23 浏览: 149
beautifulsoup用法详解.zip
以下是python中replace()函数的用法示例:
1. 替换字符串中的指定字符:
```python
str1 = "Hello, World!"
new_str = str1.replace("o", "e")
print(new_str) # 输出:Helle, Werld!
```
2. 替换字符串中的指定子字符串:
```python
str2 = "I love apples, apples are delicious."
new_str = str2.replace("apples", "oranges")
print(new_str) # 输出:I love oranges, oranges are delicious.
```
3. 替换字符串中的指定字符,指定替换次数:
```python
str3 = "Hello, World!"
new_str = str3.replace("o", "e", 1)
print(new_str) # 输出:Helle, World!
```
4. 替换DataFrame中的指定值:
```python
import pandas as pd
data = {'col1': ['apple', 'banana', 'orange'],
'col2': ['apple', 'banana', 'orange']}
df = pd.DataFrame(data)
df.replace('apple', 'kiwi', inplace=True)
print(df)
```
阅读全文