python 去除str中所有的空格和换行
时间: 2023-04-04 16:01:19 浏览: 76
可以使用replace()函数将空格和换行替换为空字符串,示例代码如下:
str = "hello world\n"
str = str.replace(" ", "").replace("\n", "")
print(str) #输出helloworld
相关问题
python 去除str中所有的空格
可以使用replace()方法将空格替换为空字符串,示例代码如下:
str = "hello world"
str = str.replace(" ", "")
print(str)
输出结果为:helloworld
Python去除空格和换行
在Python中,可以使用字符串的strip()方法去除字符串两端的空格和换行符。例如:
```
my_string = " hello world\n"
clean_string = my_string.strip()
print(clean_string)
```
输出结果为:
```
hello world
```
另外,如果想要去除字符串中的所有空格和换行符,可以使用replace()方法替换为空字符串。例如:
```
my_string = " hello world\n"
clean_string = my_string.replace(" ", "").replace("\n", "")
print(clean_string)
```
输出结果为:
```
helloworld
```