How can I remove a trailing newline?

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

    Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:

    $x="a\n";
    
    chomp $x
    

    results in $x being "a".

    but in Python:

    x="a\n"
    
    x.rstrip()
    

    will mean that the value of x is still "a\n". Even x=x.rstrip() doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.

提交回复
热议问题