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

"abc\n"  -->  "abc"

当前回答

Python文档中的一个示例简单地使用了line.strip()。

Perl的chomp函数仅在字符串末尾有一个换行符序列时才将其删除。

以下是我计划在Python中实现这一点的方法,如果process在概念上是我需要的函数,以便对该文件中的每一行执行一些有用的操作:

import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
    for line in f:
        if line[sep_pos:] == os.linesep:
            line = line[:sep_pos]
        process(line)

其他回答

Python文档中的一个示例简单地使用了line.strip()。

Perl的chomp函数仅在字符串末尾有一个换行符序列时才将其删除。

以下是我计划在Python中实现这一点的方法,如果process在概念上是我需要的函数,以便对该文件中的每一行执行一些有用的操作:

import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
    for line in f:
        if line[sep_pos:] == os.linesep:
            line = line[:sep_pos]
        process(line)

注意,rstrip的行为与Perl的chomp()不同,因为它不会修改字符串。也就是说,在Perl中:

$x="a\n";

chomp $x

结果$x为“a”。

但在Python中:

x="a\n"

x.rstrip()

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

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

特殊情况的解决方案:

如果换行符是最后一个字符(大多数文件输入都是这样),那么对于集合中的任何元素,都可以按如下方式进行索引:

foobar= foobar[:-1]

剪切换行符。