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

"abc\n"  -->  "abc"

当前回答

只需使用:

line = line.rstrip("\n")

or

line = line.strip("\n")

你不需要这些复杂的东西

其他回答

我正在从我之前在另一个答案的评论中发布的一个基于正则表达式的答案中冒泡出来。我认为使用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为假阳性,而您可能希望在删除单个尾随字符后保留其他换行符。)

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

$x="a\n";

chomp $x

结果$x为“a”。

但在Python中:

x="a\n"

x.rstrip()

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

s = '''Hello  World \t\n\r\tHi There'''
# import the module string   
import string
# use the method translate to convert 
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'

使用正则表达式

s = '''  Hello  World 
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
>HelloWorldHi

替换\n,\t,\r

s.replace('\n', '').replace('\t','').replace('\r','')
>'  Hello  World Hi '

使用正则表达式

s = '''Hello  World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello  World Hi There'

使用Join

s = '''Hello  World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello  World Hi There'

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)

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