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

"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

其他回答

在很多层面上,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'

小心使用“foo”.rstrip(os.lineep):这只会在执行Python的平台上压缩换行符。例如,假设您在Linux下敲击Windows文件的行:

$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>

请改用“foo”.rstrip(“\r\n”),如Mike所述。

尝试rstrip()方法(参见文档Python 2和Python 3)

>>> 'test string\n'.rstrip()
'test string'

Python的rstrip()方法在默认情况下去除了所有类型的尾随空格,而不是像Perl使用chomp那样只去除一行换行符。

>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'

要仅删除换行符,请执行以下操作:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

除了rstrip(),还有strip()和lstrip()方法。下面是其中三个示例:

>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'

我正在从我之前在另一个答案的评论中发布的一个基于正则表达式的答案中冒泡出来。我认为使用re比str.rstrip更明确地解决这个问题。

>>> import re

如果要删除一个或多个尾随换行符:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

如果要删除所有换行符(而不仅仅是尾部):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

如果只想删除1-2个尾随换行符(即,\r,\n,\r\n,\n\r,\r,\r\n\r\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

我有一种感觉,大多数人在这里真正想要的是只删除一个尾随换行符,\r\n或\r\n,而不是更多。

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

(?:是创建一个非捕获组。)

(顺便说一句,这不是“…”.rstrip(“\n”,“”).rstrap(“\r”,“)所做的,其他人可能不清楚这一点。str.rstrip删除尽可能多的尾随字符,因此像foo这样的字符串将导致foo为假阳性,而您可能希望在删除单个尾随字符后保留其他换行符。)

包罗万象:

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