How can I remove a trailing newline?

前端 未结 28 3276
感动是毒
感动是毒 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)
    
    0 讨论(0)
  • 2020-11-21 23:43

    I don't program in Python, but I came across an FAQ at python.org advocating S.rstrip("\r\n") for python 2.2 or later.

    0 讨论(0)
  • 2020-11-21 23:43
    >>> '   spacious   '.rstrip()
    '   spacious'
    >>> "AABAA".rstrip("A")
      'AAB'
    >>> "ABBA".rstrip("AB") # both AB and BA are stripped
       ''
    >>> "ABCABBA".rstrip("AB")
       'ABC'
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-21 23:44

    workaround solution for special case:

    if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows:

    foobar= foobar[:-1]
    

    to slice out your newline character.

    0 讨论(0)
  • 2020-11-21 23:44

    A catch all:

    line = line.rstrip('\r|\n')
    
    0 讨论(0)
提交回复
热议问题