python数据清洗空格处理
时间: 2023-08-30 12:11:08 浏览: 51
在Python中,可以使用字符串的strip()、lstrip()和rstrip()方法来清洗空格。
strip()方法可以用来清除字符串前后的空格:
```python
text = " Hello, world! "
text = text.strip()
print(text)
```
输出结果为:
```
"Hello, world!"
```
lstrip()方法可以用来清除字符串左侧的空格:
```python
text = " Hello, world! "
text = text.lstrip()
print(text)
```
输出结果为:
```
"Hello, world! "
```
rstrip()方法可以用来清除字符串右侧的空格:
```python
text = " Hello, world! "
text = text.rstrip()
print(text)
```
输出结果为:
```
" Hello, world!"
```
除了这些方法外,还可以使用正则表达式来清洗空格。例如,可以使用re模块的sub()方法来替换字符串中的空格:
```python
import re
text = " Hello, world! "
text = re.sub(r"\s+", " ", text).strip()
print(text)
```
输出结果为:
```
"Hello, world!"
```
这里的正则表达式"\s+"可以匹配一个或多个空格。使用sub()方法将其替换为一个空格,然后再使用strip()方法清除字符串前后的空格。