去除list中的空格元素
时间: 2023-04-06 19:03:45 浏览: 117
可以使用列表推导式来去除list中的空格元素,示例如下:
```python
my_list = ['hello', ' ', 'world', '', ' ', 'python']
new_list = [elem for elem in my_list if elem.strip()]
print(new_list)
```
输出结果为:
```
['hello', 'world', 'python']
```
相关问题
list去除元素中的空格
可以使用列表推导式和strip()方法来去除元素中的空格,示例代码如下:
new_list = [item.strip() for item in old_list if item.strip()]
其中,old_list为原始列表,item.strip()用于去除元素中的空格,if item.strip()用于判断元素是否为空字符串。
list去除空格java
可以使用循环遍历,判断每个元素是否为空格,然后将非空格元素添加到新的List中,示例代码如下:
```java
List<String> listWithSpaces = Arrays.asList("hello ", " world", " ", "java ");
List<String> listWithoutSpaces = new ArrayList<>();
for(String str : listWithSpaces) {
if(!str.trim().isEmpty()) {
listWithoutSpaces.add(str);
}
}
System.out.println(listWithoutSpaces); //输出 [hello, world, java]
```
在上述代码中,我们使用了 `trim()` 方法去除每个字符串的空格,然后使用 `isEmpty()` 方法判断是否为空字符串。如果不为空字符串,则将其添加到新的List中,得到一个去除空格的List。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)