在python中處理空行時,經常會遇到一些問題。現總結經驗如下:
1.遇到的空行如果只有換行符,直接使用=='/n'或者 len(line)==line.count('/n')
2.有多個空格+換行符時。有幾種處理方法:①split; ②正則表達式'^/n'(不會);③if eachLine[:-1].strip()
展開:
eg.文件過濾,顯示一個文件的所有行,忽略以井號(#)開頭的行。
①
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()
這兩種方法都可以判斷,
從同一臺電腦上讀取同樣多行的字母,相對來說,第一種方法花費了8.4s,第三種方法花費了1.6s。從實驗的角度上大概是第三種方法相對性能更優。
但具體是split()性能更優還是[:-1].strip()性能更優,有待進一步學習。
新聞熱點
疑難解答