How can I remove a trailing newline?

前端 未结 28 3507
感动是毒
感动是毒 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:02

    You may use line = line.rstrip('\n'). This will strip all newlines from the end of the string, not just one.

    0 讨论(0)
  • 2020-11-22 00:03

    Careful with "foo".rstrip(os.linesep): That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:

    $ python
    Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
    [GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os, sys
    >>> sys.platform
    'linux2'
    >>> "foo\r\n".rstrip(os.linesep)
    'foo\r'
    >>>
    

    Use "foo".rstrip("\r\n") instead, as Mike says above.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题