How can I remove a trailing newline?

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

    And I would say the "pythonic" way to get lines without trailing newline characters is splitlines().

    >>> text = "line 1\nline 2\r\nline 3\nline 4"
    >>> text.splitlines()
    ['line 1', 'line 2', 'line 3', 'line 4']
    

提交回复
热议问题