python去除字符串空格
时间: 2023-07-24 17:08:01 浏览: 44
在 Python 中,可以使用字符串的 `strip()` 方法来去除字符串两端的空格。示例代码如下:
```python
s = " hello world "
s = s.strip()
print(s) # 输出 "hello world"
```
如果只需要去除左边或者右边的空格,则可以使用 `lstrip()` 或者 `rstrip()` 方法。示例代码如下:
```python
s = " hello world "
s = s.lstrip() # 去除左边空格
print(s) # 输出 "hello world "
s = " hello world "
s = s.rstrip() # 去除右边空格
print(s) # 输出 " hello world"
```
如果需要去除字符串中间的空格,则可以使用 `replace()` 方法。示例代码如下:
```python
s = "hello world"
s = s.replace(" ", "") # 去除所有空格
print(s) # 输出 "helloworld"
```
相关问题
python 去除字符串空格
可以使用字符串的 `strip()` 方法去除字符串开头和结尾的空格,也可以使用 `replace()` 方法去除字符串中所有的空格。示例如下:
```python
# 使用 strip() 方法去除开头和结尾的空格
s = ' hello world '
s = s.strip()
print(s) # 输出:'hello world'
# 使用 replace() 方法去除所有空格
s = ' hello world '
s = s.replace(' ', '')
print(s) # 输出:'helloworld'
```
需要注意的是,`strip()` 和 `replace()` 方法都返回新的字符串,原字符串并没有被修改。如果要修改原字符串,需要将修改后的字符串赋值给原字符串。
python 去掉字符串空格
可以使用字符串的 `strip()` 方法去掉字符串两端的空格,例如:
```python
s = " hello world "
s = s.strip()
print(s) # 输出 "hello world"
```
如果只想去掉左边或右边的空格,可以使用 `lstrip()` 或 `rstrip()` 方法。例如:
```python
s = " hello world "
s = s.lstrip()
print(s) # 输出 "hello world "
s = " hello world "
s = s.rstrip()
print(s) # 输出 " hello world"
```