How can I remove a trailing newline?

前端 未结 28 3935
感动是毒
感动是毒 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条回答
  •  萌比男神i
    2020-11-22 00:05

    rstrip doesn't do the same thing as chomp, on so many levels. Read http://perldoc.perl.org/functions/chomp.html and see that chomp is very complex indeed.

    However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.

    Here you can see rstrip removing all the newlines:

    >>> 'foo\n\n'.rstrip(os.linesep)
    'foo'
    

    A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:

    >>> re.sub(os.linesep + r'\Z','','foo\n\n')
    'foo\n'
    

提交回复
热议问题