python,replace用法
时间: 2023-12-26 07:27:23 浏览: 29
以下是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)
```
相关问题
python replace用法
Python中的replace函数用于替换字符串中的某个部分。语法如下:
string.replace(old, new[, count])
参数说明:
- old: 需要被替换的部分
- new: 新的内容
- count: 替换的次数,默认为替换所有
示例:
str1 = "Hello World"
str2 = str1.replace("World", "Python")
print(str2)
输出: Hello Python
请注意,replace方法会返回一个新的字符串,而不会更改原始字符串。如果需要更改原始字符串,可以将返回值赋值给原始字符串变量。
python replace 用法
在 Python 中,你可以使用字符串的 `replace()` 方法来替换子串。例如:
```
string = "Hello World"
# Replace "World" with "China"
string = string.replace("World", "China")
print(string) # "Hello China"
```
你还可以使用正则表达式来替换字符串,例如:
```
import re
string = "Hello World"
# Replace all letters "o" with "0"
string = re.sub("o", "0", string)
print(string) # "Hell0 W0rld"
```
你也可以使用 `translate()` 方法来替换字符串中的某些字符。例如:
```
import string
string = "Hello World"
# Create a translation table to replace all vowels with "X"
translator = string.maketrans("AEIOUaeiou", "XXXXXxxxxx")
string = string.translate(translator)
print(string) # "HXllX WXrld"
```