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

"abc\n"  -->  "abc"

当前回答

在很多层面上,rstrip做的事情与chomp不同。阅读http://perldoc.perl.org/functions/chomp.html看到chomp确实非常复杂。

然而,我的主要观点是chomp最多删除1行结尾,而rstrip将删除尽可能多的结尾。

在这里,您可以看到rstrip删除了所有换行符:

>>> 'foo\n\n'.rstrip(os.linesep)
'foo'

使用re.sub可以更接近典型的Perl chomp用法,如下所示:

>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'

其他回答

包罗万象:

line = line.rstrip('\r|\n')

只需使用:

line = line.rstrip("\n")

or

line = line.strip("\n")

你不需要这些复杂的东西

>>> '   spacious   '.rstrip()
'   spacious'
>>> "AABAA".rstrip("A")
  'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
   ''
>>> "ABCABBA".rstrip("AB")
   'ABC'

如果您的问题是清除多行str对象(oldstr)中的所有换行符,您可以根据分隔符“\n”将其拆分为一个列表,然后将此列表合并为一个新的str(newstr)。

newstr=“”.jjoin(oldstr.split('\n'))

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