python 删除列表中的空字符串
时间: 2023-09-04 09:12:01 浏览: 49
可以使用列表解析的方式来删除列表中的空字符串,代码如下:
```python
my_list = ["hello", "", "world", "", " ", "python", ""]
new_list = [x for x in my_list if x != ""]
print(new_list)
```
输出结果为:
```
['hello', 'world', ' ', 'python']
```
在列表解析中,我们遍历原始列表 `my_list` ,将非空字符串添加到新列表 `new_list` 中。如果遇到空字符串,则不添加。
相关问题
python删除字符串列表中的空字符串
可以使用`filter()`函数和`lambda`表达式来删除字符串列表中的空字符串,示例代码如下:
```python
str_list = ['hello', '', 'world', '', 'python', '']
str_list = list(filter(lambda x: x != '', str_list))
print(str_list)
```
输出结果为:
```
['hello', 'world', 'python']
```
在这个示例代码中,`filter()`函数会依次遍历`str_list`列表中的每一个元素,并根据`lambda`表达式的返回值来决定是否保留该元素。`lambda x: x != ''`表示当元素不是空字符串时返回`True`,否则返回`False`。由于`filter()`函数只会保留返回值为`True`的元素,因此最终结果中不包含空字符串。最后,使用`list()`函数将`filter()`函数返回的迭代器转换为列表。
python删除字符串中字符
要删除字符串中的字符,可以使用Python的字符串函数replace(),它可以将字符串中的所有指定字符替换为其他字符或删除字符。例如,下面的代码将从字符串中删除所有的字母e:
``` python
string = "Hello, world!"
new_string = string.replace("e", "")
print(new_string)
```
输出结果为:
```
Hllo, world!
```
另外,如果你想删除字符串中的所有空格,可以使用字符串函数replace()将空格替换为一个空字符串,如下所示:
``` python
string = " Hello, world! "
new_string = string.replace(" ", "")
print(new_string)
```
输出结果为:
```
Hello,world!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)