How can I remove a trailing newline?

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

    This would replicate exactly perl's chomp (minus behavior on arrays) for "\n" line terminator:

    def chomp(x):
        if x.endswith("\r\n"): return x[:-2]
        if x.endswith("\n") or x.endswith("\r"): return x[:-1]
        return x
    

    (Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \r\n in account)

提交回复
热议问题