Idiomatic portable way to strip line endings?

Jason Orendorff jason at jorendorff.com
Sun Dec 16 14:53:19 EST 2001


> I've been trying to figure out the canonical way to strip
> the line endings from a text file.

There isn't one.  Almost always, either rstrip() is sufficient,
*or* you're doing text slinging, in which case you can leave the
newline characters on there, do the regex stuff, and file.write()
the lines out the same way they came in.

That said, the function you want is:

  def chomp(line):
      if line.endswith('\r\n'):
          return line[:-2]
      elif line.endswith('\r') or line.endswith('\n'):
          return line[:-1]
      else:
          return line

If you're getting these strings from a text file, you could:

  for unstripped_line in file:
      for line in unstripped_line.splitlines():
          ...process line...

Why is this necessary?  Unfortunately readline() doesn't
interpret a bare '\r' as a line ending on Windows or Unix.
So if the file contains bare '\r's, then the above code
will read the entire file into the unstripped_line
variable, then break it into lines with splitlines().

-- 
Jason Orendorff    http://www.jorendorff.com/





More information about the Python-list mailing list