Replace multiple newlines with single newlines during reading file

前端 未结 3 1131
梦毁少年i
梦毁少年i 2021-02-14 11:55

I have the next code which reads from multiple files, parses obtained lines and prints the result:

import os
import re

files=[]
pars=[]

for i in os.listdir(\'pa         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 12:11

    Just would like to point out: regexes aren't the best way to handle that. Replacing two empty lines by one in a Python str is quite simple, no need for re:

    entire_file = "whatever\nmay\n\nhappen"
    entire_file = entire_file.replace("\n\n", "\n")
    

    And voila! Much faster than re and (in my opinion) much easier to read.

提交回复
热议问题