python去除列表内容空格方法
时间: 2023-07-29 15:08:23 浏览: 43
你可以使用列表解析和字符串的 `strip()` 方法来去除列表中元素的空格。下面是一个示例代码:
```python
my_list = [' apple ', ' banana ', ' orange ']
new_list = [x.strip() for x in my_list]
print(new_list)
```
输出:
```
['apple', 'banana', 'orange']
```
在这个例子中,`strip()` 方法被用于去除每个元素的前后空格。你可以根据需要使用其他字符串方法来处理列表中的元素。
相关问题
python去除字符串空格
在 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()` 方法都返回新的字符串,原字符串并没有被修改。如果要修改原字符串,需要将修改后的字符串赋值给原字符串。