python中str去除空格
时间: 2024-01-10 12:21:57 浏览: 23
在Python中,可以使用strip()方法去除字符串两端的空格,也可以使用replace()方法将字符串中的空格替换为空。例如:
```python
str1 = " hello world "
# 使用strip()方法去除两端空格
str2 = str1.strip()
print(str2) # 输出:"hello world"
# 使用replace()方法将空格替换为空
str3 = str1.replace(" ", "")
print(str3) # 输出:"helloworld"
```
除了strip()和replace()方法外,还可以使用正则表达式或者split()方法去除字符串中的空格。
相关问题
python 去除str中所有的空格
可以使用replace()方法将空格替换为空字符串,示例代码如下:
str = "hello world"
str = str.replace(" ", "")
print(str)
输出结果为:helloworld
python 去除str中所有的空格和换行
可以使用replace()函数将空格和换行替换为空字符串,示例代码如下:
str = "hello world\n"
str = str.replace(" ", "").replace("\n", "")
print(str) #输出helloworld