python字符串去空格
时间: 2023-08-27 09:12:22 浏览: 41
在Python中,你可以使用字符串的 `strip()` 方法去除字符串两端的空格,或者使用 `replace()` 方法替换字符串中的空格。
下面是两种方法的示例代码:
1. 使用 `strip()` 方法去除字符串两端的空格:
```python
string = " Hello, World! "
stripped_string = string.strip()
print(stripped_string)
相关问题
python字符串去除空格
可以使用 `strip()` 方法去除字符串两端的空格,也可以使用 `replace()` 方法将字符串中的空格替换为空字符。例如:
```python
s = ' hello world '
s = s.strip() # 去除两端空格
print(s) # 输出:'hello world'
s = ' hello world '
s = s.replace(' ', '') # 将空格替换为空字符
print(s) # 输出:'helloworld'
```
如果你想去除字符串中所有空格,而不仅仅是两端的空格,可以使用正则表达式来实现:
```python
import re
s = ' hello world '
s = re.sub(r'\s+', '', s) # 将所有空格替换为空字符
print(s) # 输出:'helloworld'
```
Python字符串去空格
可以使用字符串的 `strip()` 方法去除字符串首尾的空格,例如:
```python
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
```
如果只想去除字符串开头或结尾的空格,可以使用 `lstrip()` 或 `rstrip()` 方法。`lstrip()` 方法用于去除字符串开头的空格,`rstrip()` 方法用于去除字符串结尾的空格。例如:
```python
s = " hello world "
s = s.lstrip()
print(s) # 输出:hello world
s = " hello world "
s = s.rstrip()
print(s) # 输出: hello world
```