How can I remove a trailing newline?

前端 未结 28 4204
感动是毒
感动是毒 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-21 23:52

    Try the method rstrip() (see doc Python 2 and Python 3)

    >>> 'test string\n'.rstrip()
    'test string'
    

    Python's rstrip() method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp.

    >>> 'test string \n \r\n\n\r \n\n'.rstrip()
    'test string'
    

    To strip only newlines:

    >>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
    'test string \n \r\n\n\r '
    

    There are also the methods strip(), lstrip() and strip():

    >>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
    >>> s.strip()
    'abc   def'
    >>> s.lstrip()
    'abc   def \n\r\n  \n  '
    >>> s.rstrip()
    '   \n\r\n  \n  abc   def'
    

提交回复
热议问题