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

"abc\n"  -->  "abc"

当前回答

去除行尾(EOL)字符的规范方法是使用string rstrip()方法删除任何尾随的\r\n或。以下是Mac、Windows和Unix EOL字符的示例。

>>> 'Mac EOL\r'.rstrip('\r\n')
'Mac EOL'
>>> 'Windows EOL\r\n'.rstrip('\r\n')
'Windows EOL'
>>> 'Unix EOL\n'.rstrip('\r\n')
'Unix EOL'

使用“\r\n”作为rstrip的参数意味着它将去掉“\r”或“\n”的任何尾随组合。这就是为什么它在上述三种情况下都有效。

这种细微差别在极少数情况下很重要。例如,我曾经不得不处理一个包含HL7消息的文本文件。HL7标准要求结尾“\r”作为其EOL字符。使用此消息的Windows计算机已附加了自己的“\r\n”EOL字符。因此,每行的结尾看起来像“\r\n”。使用rstrip(“\r\n”)会删除整个“\r\n”,这不是我想要的。在这种情况下,我只是把最后两个字符切下来。

注意,与Perl的chomp函数不同,这将去掉字符串末尾的所有指定字符,而不仅仅是一个:

>>> "Hello\n\n\n".rstrip("\n")
"Hello"

其他回答

import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)

我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。

您可以使用strip:

line = line.strip()

演示:

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

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

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)

如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比rstrip更快。一个小测试来说明这一点:

import time

loops = 50000000

def method1(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string[:-1]
    t1 = time.time()
    print('Method 1: ' + str(t1 - t0))

def method2(loops=loops):
    test_string = 'num\n'
    t0 = time.time()
    for num in xrange(loops):
        out_sting = test_string.rstrip()
    t1 = time.time()
    print('Method 2: ' + str(t1 - t0))

method1()
method2()

输出:

Method 1: 3.92700004578
Method 2: 6.73000001907