How Python deletes all whitespace items in a list

Source: Internet
Author: User
Below for you to share a Python delete the list of all the blanks in the method summary, with a good reference value, I hope to be helpful to everyone. Come and see it together.

First, let's write a list with spaces:

List1 = [' 122 ', ' 2333 ', ' 3444 ', ' ', ' 422 ', ', ', ' 54 ', ']

Believe that someone has tried, such as the following ways to delete the space, for example:

#-*-Coding:utf-8-*-for i in list1:if i = = ": List1.remove (") Print List1

But the result you will find is this, it always can not completely delete the space, will be left at the end of a.

Method One:

At this time, you can try to change ' = = ' to In:

#-*-Coding:utf-8-*-for i in List1:if "in List1:list1.remove (") Print List1

Before I saw on the internet with the "Join way, the link can not find, this method it does delete the empty string with a length", but for the interval comparison of the law, the interval is not very good, and regardless of the interval law or not, it will generate 0 length ' empty string.

Method Two:

Method One is later to write this article when the test article at the beginning of the wrong way of writing, because remember not too clear, inadvertently thought of in, the results found that the result is right, my own first thought of the method is such, first get the number of spaces, and then traverse, delete one by one:

For I in Range (List1.count (")): List1.remove (")

Method Three:

And then used for me just wondering if I could use while, how to write with while, and test what I found out:

While "in List1:list1.remove (") Print List1

The above is a relatively early write, with most of the remove, now learn some optimization, and then add comments in the hints, only to find the derivation can also, thanks!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.