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

"abc\n"  -->  "abc"

当前回答

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

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

其他回答

小心使用“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'

去除行尾(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"

如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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的行为与Perl的chomp()不同,因为它不会修改字符串。也就是说,在Perl中:

$x="a\n";

chomp $x

结果$x为“a”。

但在Python中:

x="a\n"

x.rstrip()

将意味着x的值仍然是“a \n”。即使x=x.rstrip()也不总是给出相同的结果,因为它会从字符串末尾删除所有空格,而不是最多一个换行符。