The problem of removing empty lines in Python

Source: Internet
Author: User

When working with empty lines in Python, you often encounter problems. Lessons learned are as follows:

1. If you encounter a blank line with a newline character, use the = = ' \ n ' or Len (line) ==line.count (' \ n ')

2. When there are more than one space + line break. There are several processing methods: ①split;② Regular expression ' ^\n ' (not); ③if Eachline[:-1].strip ()

Expand

eg. file filtering, which displays all lines of a file, ignoring lines that begin with a pound sign (#).

1F=open ('Test.txt','R')2  forEachlineinchF:3     if  notEachline.split ():#whether space4         PrintEachline,5     elifEachline.strip () [0]!='#':6         PrintEachline,7 8F.close ()

1F=open ('Test.txt','R')2  forEachlineinchF:3     if  notEachline[:-1].strip ():#whether space4         PrintEachline,5     elifEachline.strip () [0]!='#':6         PrintEachline,7 8F.close ()

Both of these methods can be judged,

Reading the same many lines of letters from the same computer, the first method costs 8.4s, and the third method costs 1.6s. From the experimental point of view is probably the third method of relative performance better.

But specifically, split () better performance or [: -1].strip () better performance, pending further study.

The problem of removing empty lines in Python

Related Article

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.