Remove empty rows in python. Remove empty rows in python.

Source: Internet
Author: User

Remove empty rows in python. Remove empty rows in python.

When processing empty rows in python, some problems are often encountered. The summary is as follows:

1. If the blank line is only a line break, use = '\ n' or len (line) = line. count (' \ n ')

2. When there are multiple spaces + line breaks. There are several Processing Methods: ① split; ② regular expression '^ \ n' (NO); ③ if eachLine [:-1]. strip ()

 

Expand:

For example, if the file is filtered out, all rows of a file are displayed, and the rows starting with the pound sign (#) are ignored.

①

1 f=open('test.txt ', 'R') 2 for eachLine in f: 3 if not eachLine. split (): # whether space4 print eachLine, 5 elif eachLine. strip () [0]! = '#': 6 print eachLine, 7 8 f. close ()

③

1 f=open('test.txt ', 'R') 2 for eachLine in f: 3 if not eachLine [:-1]. strip (): # whether space4 print eachLine, 5 elif eachLine. strip () [0]! = '#': 6 print eachLine, 7 8 f. close ()

Both methods can be judged,

Reading the same number of rows of letters from the same computer takes 8.4 s for the first method and 1.6 s for the third method. From the perspective of experiments, the third method is relatively better.

However, [:-1]. strip () has better performance and needs further study.

 

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.