Python method to delete all space items in a list

不言
Release: 2018-04-18 11:21:55
Original
4366 people have browsed it

The following is a summary of how to delete all space items in a list in python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

First of all, let’s just write a list with spaces:

list1 = ['122','2333','3444',' ','422',' ',' ','54',' ']
Copy after login

I believe someone has already tried it, such as the following method to delete spaces, for example:

# -*- coding:utf-8 -*- for i in list1: if i == ' ': list1.remove(' ') print list1
Copy after login

But the result is that you will find that it cannot completely delete the spaces and will end up at the end. Leave one behind.

Method 1:

At this time, you can try changing '==' to in:

# -*- coding:utf-8 -*- for i in list1: if ' ' in list1: list1.remove(' ') print list1
Copy after login

# I have seen the ''join method on the Internet before, but the link cannot be found. This method does not work It can indeed delete empty strings with a length of ' ', but it is good for regular intervals. It is not so friendly for irregular intervals, and it will generate an empty string of zero length ' ' regardless of whether the intervals are regular or not. of.

Method 2:

Method 1 was when I was writing this article later to test the wrong way of writing at the beginning of the article, because I remembered Not sure, I accidentally thought of in, and found that the result was correct. The first method I thought of was this, first get the number of spaces, then traverse and delete them one by one:

for i in range(list1.count(' ')): list1.remove(' ')
Copy after login

Method three:

#Then I used for and I was wondering if it was possible Use while, how to write while, I tested it and found that it works:

while ' ' in list1: list1.remove(' ') print list1
Copy after login

The above was written relatively early. , I mostly use remove. Now that I have learned some optimizations and added the tips in the comments, I found that derivation can also be used. Thank you!

Related recommendations:

How to delete files and directories in Python


The above is the detailed content of Python method to delete all space items in a list. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!