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

"abc\n"  -->  "abc"

当前回答

如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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

其他回答

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

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

或者你可以用regexp变得更古怪

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

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

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

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)

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

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