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