How can I remove a trailing newline?

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

提交回复
热议问题