Categories
newline python trailing

How do I remove a trailing newline?

1938

How do I remove the last character of a string if it is a newline?

"abc\n"  -->  "abc"

2

183

And I would say the “pythonic” way to get lines without trailing newline characters is splitlines().

>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

3

  • 7

  • This also gives unexpected results if you have a multi-line string and only want to strip the last line-terminator…. (although it can probably by joined back again for that)

    Dec 31, 2021 at 19:27

  • @GertvandenBerg the method is called splitlines(). If I give it a multi-line string, I don’t expect it to strip only the last line, because I literaly told it to split my multi-line string into multiple strings at the line breaks 😉 Using it to strip line endings off a single-line string is actually just a useful corner case.

    – SvenS

    May 5 at 10:51

164

The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n. Here are examples for Mac, Windows, and Unix EOL characters.

>>> 'Mac EOL\r'.rstrip('\r\n')
'Mac EOL'
>>> 'Windows EOL\r\n'.rstrip('\r\n')
'Windows EOL'
>>> 'Unix EOL\n'.rstrip('\r\n')
'Unix EOL'

Using ‘\r\n’ as the parameter to rstrip means that it will strip out any trailing combination of ‘\r’ or ‘\n’. That’s why it works in all three cases above.

This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing ‘\r’ as its EOL character. The Windows machine on which I was using this message had appended its own ‘\r\n’ EOL character. Therefore, the end of each line looked like ‘\r\r\n’. Using rstrip(‘\r\n’) would have taken off the entire ‘\r\r\n’ which is not what I wanted. In that case, I simply sliced off the last two characters instead.

Note that unlike Perl’s chomp function, this will strip all specified characters at the end of the string, not just one:

>>> "Hello\n\n\n".rstrip("\n")
"Hello"

8

  • 7

    Note that modern Mac OS X apps use \n. Only old Carbon apps originally written for Mac OS use \r.

    Nov 9, 2008 at 6:15

  • 2

    Thanks for the clarification. Of course, the rstrip(‘\r\n’) still works in that case too.

    – Mike

    Nov 9, 2008 at 11:35

  • 14

    There’s also os.linesep, which contains the EOL sequence for the current OS.

    Aug 15, 2011 at 13:44


  • This is the best answer: It only strips newlines, and does it correctly for the most common platforms.

    – kevinarpe

    Feb 12, 2015 at 3:58

  • plus +1 For using \n and \r

    – fechnert

    May 28, 2015 at 15:35