尝试使用rstrip()
方法(请参阅 doc 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 '
还有方法lstrip()
和strip()
:
>>> 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'
我想说的是,在不尾随换行符的情况下获取行的 “pythonic” 方法是 splitlines()。
>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']
删除行尾(EOL)字符的规范方法是使用字符串 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 \ r \ n'。使用 rstrip('\ r \ n')会删除整个 '\ r \ r \ n',这不是我想要的。在那种情况下,我只是切掉了最后两个字符。
请注意,与 Perl 的chomp
函数不同,这将在字符串的末尾剥离所有指定的字符,而不仅仅是一个:
>>> "Hello\n\n\n".rstrip("\n")
"Hello"
请注意,rstrip 的行为与 Perl 的 chomp()并不完全相同,因为它不会修改字符串。也就是说,在 Perl 中:
$x="a\n";
chomp $x
结果$x
为"a"
。
但在 Python 中:
x="a\n"
x.rstrip()
表示x
的值仍为 "a\n"
。甚至x=x.rstrip()
也不总是给出相同的结果,因为它从字符串的末尾x=x.rstrip()
所有空格,最多不只是一个换行符。
我可能会使用这样的东西:
import os
s = s.rstrip(os.linesep)
我认为rstrip("\n")
的问题在于您可能要确保行分隔符是可移植的。 (谣传某些过时的系统使用"\r\n"
)。另一个rstrip
是rstrip
会rstrip
重复的空格。希望os.linesep
将包含正确的字符。以上对我有用。
您可以使用line = line.rstrip('\n')
。这将从字符串末尾除去所有换行符,而不仅仅是一条。
s = s.rstrip()
将删除字符串s
末尾的所有换行符。需要分配是因为rstrip
返回一个新字符串,而不是修改原始字符串。
这将为 “\ n” 行终止符精确复制 perl 的 champ(数组的负行为):
def chomp(x):
if x.endswith("\r\n"): return x[:-2]
if x.endswith("\n") or x.endswith("\r"): return x[:-1]
return x
(注意:它不会修改字符串 “就地”;它不会去除多余的尾随空格;需要考虑 \ r \ n)
您可以使用地带:
line = line.strip()
演示:
>>> "\n\n hello world \n\n".strip()
'hello world'
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
否则您总是可以通过 regexp 变得更加怪异:)
玩得开心!