Python如何去除空格
时间: 2023-08-31 12:10:04 浏览: 38
在Python中,可以使用strip()方法去除字符串开头和结尾的空格,或使用replace()方法去除字符串中所有的空格。
例如:
```python
# 去除字符串开头和结尾的空格
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
# 去除字符串中所有的空格
s = " hello world "
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
另外,如果需要去除指定位置的空格,可以使用字符串切片操作或正则表达式等方法。
相关问题
python去除空格
可以使用`strip()`函数去除列空格,例如:
```python
import pandas as pd
# 创建示例数据
data = {'col1': [' a', 'b ', ' c '], 'col2': [1, 2, 3]}
df = pd.DataFrame(data)
# 去除col1列的空格
df['col1'] = df['col1'].str.strip()
print(df)
```
输出结果为:
```
col1 col2
0 a 1
1 b 2
2 c 3
```
python 去除空格
可以使用字符串的 strip() 方法去除字符串两端的空格,或者使用 replace() 方法将字符串中的空格替换为空。例如:
```python
s = " Hello, world! "
s = s.strip() # 去除两端的空格
print(s) # 输出 "Hello, world!"
s = "Hello, world!"
s = s.replace(" ", "") # 将空格替换为空
print(s) # 输出 "Hello,world!"
```