How can I remove a trailing newline?

前端 未结 28 3613
感动是毒
感动是毒 2020-11-21 23:27

What is the Python equivalent of Perl\'s chomp function, which removes the last character of a string if it is a newline?

28条回答
  •  终归单人心
    2020-11-22 00:05

    I might use something like this:

    import os
    s = s.rstrip(os.linesep)
    

    I think the problem with rstrip("\n") is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use "\r\n"). The other gotcha is that rstrip will strip out repeated whitespace. Hopefully os.linesep will contain the right characters. the above works for me.

提交回复
热议问题