Python输出去掉空格
时间: 2023-10-16 20:17:09 浏览: 120
您可以使用Python中的strip()方法去掉字符串开头和结尾的空格,或者使用replace()方法去掉所有空格。以下是两种方法的示例:
使用strip()方法:
```python
string_with_spaces = " Hello, world! "
string_without_spaces = string_with_spaces.strip()
print(string_without_spaces)
```
输出:
```
Hello, world!
```
使用replace()方法:
```python
string_with_spaces = " Hello, world! "
string_without_spaces = string_with_spaces.replace(" ", "")
print(string_without_spaces)
```
输出:
```
Hello,world!
```
相关问题
python最后输出怎么去掉空格
如果你想要在输出时去掉字符串末尾的空格,可以使用 `rstrip()` 方法。例如:
```
s = "Hello World "
print(s.rstrip())
```
输出结果为:
```
Hello World
```
如果你想要去掉字符串中所有的空格,可以使用 `replace()` 方法。例如:
```
s = "Hello World "
print(s.replace(" ", ""))
```
输出结果为:
```
HelloWorld
```
Python如何去除空格
在Python中,可以使用strip()方法去除字符串开头和结尾的空格,或使用replace()方法去除字符串中所有的空格。
例如:
```python
# 去除字符串开头和结尾的空格
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
# 去除字符串中所有的空格
s = " hello world "
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
另外,如果需要去除指定位置的空格,可以使用字符串切片操作或正则表达式等方法。