How can I remove a trailing newline?

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

    I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:

    def chomped_lines(it):
        return map(operator.methodcaller('rstrip', '\r\n'), it)
    

    Sample usage:

    with open("file.txt") as infile:
        for line in chomped_lines(infile):
            process(line)
    

提交回复
热议问题