How can I remove a trailing newline?

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

    It looks like there is not a perfect analog for perl's chomp. In particular, rstrip cannot handle multi-character newline delimiters like \r\n. However, splitlines does as pointed out here. Following my answer on a different question, you can combine join and splitlines to remove/replace all newlines from a string s:

    ''.join(s.splitlines())
    

    The following removes exactly one trailing newline (as chomp would, I believe). Passing True as the keepends argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last "line":

    def chomp(s):
        if len(s):
            lines = s.splitlines(True)
            last = lines.pop()
            return ''.join(lines + last.splitlines())
        else:
            return ''
    

提交回复
热议问题