Search code examples
pythonstringpython-3.xif-statementblank-line

Why line != "\n" or line != "\r\n" or line !="\r" can't filte blank line?


Blank line contain only \n or \r\n or \r.

tempfile = open(file,"r")
for id,line in  enumerate(tempfile):
    if(line != "\n" or line != "\r\n" or line !="\r"):
        print(id,line)

Why blank line can be still printed?


Solution

  • The

    if(line != "\n" or line != "\r\n" or line !="\r"):
    

    should read

    if line != "\n" and line != "\r\n" and line !="\r":
    

    i.e. using and instead of or. (I've also removed the parentheses as they are not needed in Python.)

    The same expression can be written more idiomatically like so:

    if line not in {"\n", "\r\n", "\r"}:
    

    Or perhaps even:

    if line.rstrip("\r\n"):
    

    (This removes all trailing CR and LF characters and then checks whether anything remains.)