Perl's chomp() equivalent for removing trailing newlines from strings in python

By: Python Documentation Team Viewed: 153250 times  Printer Friendly Format    

Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurrences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:

>>> lines = ("line 1 \r\n"
...          "\r\n"
...          "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '

Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well.

For older versions of Python, there are two partial substitutes:

  • If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline.
  • Otherwise, if there is only one line in the string S, use S.splitlines()[0].

Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial