如果字符串是换行符,我如何删除它的最后一个字符?

"abc\n"  -->  "abc"

当前回答

我发现,通过迭代器获取压缩行很方便,与从文件对象获取未压缩行的方式类似。您可以使用以下代码执行此操作:

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

示例用法:

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

其他回答

我可以说,在没有换行符的情况下获取行的“pythonic”方法是splitlines()。

>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

我们通常会遇到三种类型的行尾:\n、\r\n和\r\n。re.sub中的一个相当简单的正则表达式,即r“\r?\n?$”,能够将它们全部捕获。

(我们必须抓住他们,对吗?)

import re

re.sub(r"\r?\n?$", "", the_text, 1)

在最后一个论点中,我们将替换的发生次数限制为一次,在某种程度上模仿了chomp。例子:

import re

text_1 = "hellothere\n\n\n"
text_2 = "hellothere\n\n\r"
text_3 = "hellothere\n\n\r\n"

a = re.sub(r"\r?\n?$", "", text_1, 1)
b = re.sub(r"\r?\n?$", "", text_2, 1)
c = re.sub(r"\r?\n?$", "", text_3, 1)

…其中a==b==c为True。


这将适用于windows和linux(如果您只寻找重新解决方案,那么使用re-sub有点贵)

import re 
if re.search("(\\r|)\\n$", line):
    line = re.sub("(\\r|)\\n$", "", line)

Python文档中的一个示例简单地使用了line.strip()。

Perl的chomp函数仅在字符串末尾有一个换行符序列时才将其删除。

以下是我计划在Python中实现这一点的方法,如果process在概念上是我需要的函数,以便对该文件中的每一行执行一些有用的操作:

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)

您可以使用strip:

line = line.strip()

演示:

>>> "\n\n hello world \n\n".strip()
'hello world'