如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"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']
其他回答
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()方法(参见文档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'
对于perl的chomp,似乎没有完美的模拟。特别是,rstrip不能处理像\r\n这样的多字符换行符。然而,分裂线确实如这里所指出的那样。根据我对另一个问题的回答,您可以组合连接和拆分线来删除/替换字符串中的所有换行符:
''.join(s.splitlines())
下面只删除了一个尾随换行符(我相信chomp会这样做)。将True作为keeponds参数传递给拆分线将保留分隔符。然后,再次调用拆分线以删除最后一行上的分隔符:
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''
去除行尾(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"
只需使用:
line = line.rstrip("\n")
or
line = line.strip("\n")
你不需要这些复杂的东西