How can I remove a trailing newline?

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

    An example in Python's documentation simply uses line.strip().

    Perl's chomp function removes one linebreak sequence from the end of a string only if it's actually there.

    Here is how I plan to do that in Python, if process is conceptually the function that I need in order to do something useful to each line from this file:

    import os
    sep_pos = -len(os.linesep)
    with open("file.txt") as f:
        for line in f:
            if line[sep_pos:] == os.linesep:
                line = line[:sep_pos]
            process(line)
    

提交回复
热议问题