如何在Python中删除尾部换行符?
什么是Perl的chomp函数的Python等价物,如果它是换行符,它会删除字符串的最后一个字符?
26个解决方案
1473 votes
尝试方法lstrip()(参见doc Python 2和Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python的lstrip()方法默认情况下会删除所有类型的尾随空格,而不仅仅是Perl与lstrip()一样的新行。
>>> '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'
Markus Jarderot answered 2019-03-24T22:21:01Z
143 votes
而且我会说“pythonic”获取没有尾随换行符的行的方法是splitlines()。
>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']
Ryan Ginstrom answered 2019-03-24T22:21:29Z
130 votes
剥离行尾(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标准要求尾随'\ n'作为其EOL字符。 我使用此消息的Windows机器附加了自己的'\ r \ n'EOL字符。 因此,每行的结尾看起来像'\ r \ n \ r \ n'。 使用rstrip('\ r \ n')会取消整个'\ r \ n \ n \ n',这不是我想要的。 在那种情况下,我只是将最后两个字符切掉。
请注意,与Perl的chomp函数不同,这将删除字符串末尾的所有指定字符,而不仅仅是一个:
>>> "Hello\n\n\n".rstrip("\n")
"Hello"
Mike answered 2019-03-24T22:22:17Z
96 votes
请注意,rstrip的行为与Perl的chomp()完全不同,因为它不会修改字符串。 也就是说,在Perl中:
$x="a\n";
chomp $x
结果在x是"a\n"。
但在Python中:
x="a\n"
x.rstrip()
将意味着x的值仍然是"a\n".即使x=x.rstrip()也不总是给出相同的结果,因为它从字符串的末尾剥离所有空格,而不是最多只有一个换行符。
Flimm answered 2019-03-24T22:23:04Z
46 votes
我可能会使用这样的东西:
import os
s = s.rstrip(os.linesep)
我认为rstrip("\n")的问题在于您可能希望确保行分隔符是可移植的。 (传闻一些陈旧的系统使用"\r\n")。 另一个问题是,rstrip将删除重复的空格。 希望os.linesep将包含正确的字符。 以上对我有用。
Jamie answered 2019-03-24T22:23:38Z
37 votes
您可以使用line = line.rstrip('\n').这将从字符串末尾删除所有换行符,而不只是一行。
octoback answered 2019-03-24T22:24:05Z
29 votes
s = s.rstrip()
将删除字符串s末尾的所有换行符。需要赋值,因为rstrip返回一个新字符串而不是修改原始字符串。
slec answered 2019-03-24T22:24:34Z
24 votes
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
或者你可以随时使用regexps :)
玩得开心!
mihaicc answered 2019-03-24T22:25:07Z
20 votes
你可以使用strip:
line = line.strip()
演示:
>>> "\n\n hello world \n\n".strip()
'hello world'
Hackaholic answered 2019-03-24T22:25:38Z
19 votes
小心"foo".rstrip("\r\n"):这只会扼杀正在执行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"),正如迈克上面所说。
Carlos Valiente answered 2019-03-24T22:26:19Z
18 votes
Python文档中的一个示例仅使用process。
Perl的process函数只在字符串末尾删除了一个换行符序列,只要它实际存在。
以下是我计划在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)
minopret answered 2019-03-24T22:27:02Z
18 votes
这将为“\ n”行终止符完全复制perl的chomp(减去数组上的行为):
def chomp(x):
if x.endswith("\r\n"): return x[:-2]
if x.endswith("\n") or x.endswith("\r"): return x[:-1]
return x
(注意:它不会修改字符串'in place';它不会删除额外的尾随空格;在帐户中取\ r \ n)
Alien Life Form answered 2019-03-24T22:27:39Z
15 votes
在很多层面上,rstrip与chomp不同。 阅读[http://perldoc.perl.org/functions/chomp.html],看看chomp确实非常复杂。
但是,我的主要观点是chomp最多删除1行结束,而rstrip将删除尽可能多的行。
在这里你可以看到删除所有新行的rstrip:
>>> 'foo\n\n'.rstrip(os.linesep)
'foo'
使用re.sub可以更加接近典型的Perl chomp用法,如下所示:
>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'
ingydotnet answered 2019-03-24T22:28:28Z
13 votes
我不用Python编程,但是我在python.org上遇到了一个常见问题解答,主张用于python 2.2或更高版本的S.rstrip(“\ r \ n”)。
Andrew Grimm answered 2019-03-24T22:28:56Z
9 votes
import re
r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)
Halit Alptekin answered 2019-03-24T22:29:17Z
7 votes
解决特殊情况的解决方案:
如果换行符是最后一个字符(与大多数文件输入的情况一样),那么对于集合中的任何元素,您可以索引如下:
foobar= foobar[:-1]
切出你的换行符。
Chij answered 2019-03-24T22:29:58Z
7 votes
如果您的问题是清除多行str对象(oldstr)中的所有换行符,则可以根据分隔符'\ n'将其拆分为列表,然后将此列表连接到新的str(newstr)。
newstr = "".join(oldstr.split('\n'))
Leozj answered 2019-03-24T22:30:34Z
5 votes
我发现能够通过迭代器获取chomped行很方便,与从文件对象中获取未选择行的方式并行。 您可以使用以下代码执行此操作:
def chomped_lines(it):
return map(operator.methodcaller('rstrip', '\r\n'), it)
样品用法:
with open("file.txt") as infile:
for line in chomped_lines(infile):
process(line)
kuzzooroo answered 2019-03-24T22:31:05Z
4 votes
看起来perl的chomp没有完美的模拟。 特别是,rstrip不能处理像True这样的多字符换行分隔符。但是,分割线就像这里指出的那样。根据我对其他问题的回答,您可以结合使用join和splitlines来删除/替换字符串keepends中的所有换行符:
''.join(s.splitlines())
以下删除了一个尾随换行符(我相信chomp会这样)。 传递True作为splitlines的keepends参数保留分隔符。 然后,再次调用splitlines以删除最后一行“分隔符”:
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''
user3780389 answered 2019-03-24T22:31:42Z
4 votes
我正在鼓励我从前面在另一个答案的评论中发布的一个基于正则表达式的答案。 我认为使用'...'.rstrip('\n', '').rstrip('\r', '')比str.rstrip更清晰,更明确地解决了这个问题。
>>> import re
如果要删除一个或多个尾随换行符:
>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'
如果你想删除所有地方的换行符(不仅仅是尾随):
>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'
如果你想只删除1-2个尾随换行符(即'...'.rstrip('\n', '').rstrip('\r', ''),str.rstrip,foo\n\n\n,foo,\r\r,\n\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'
我有一种感觉,大多数人真正想要的是,只删除一个尾随换行符的一个出现,'...'.rstrip('\n', '').rstrip('\r', '')或str.rstrip,仅此而已。
>>> 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', '').rstrip('\r', '')用于创建非捕获组。)
(顺便说一下,这不是'...'.rstrip('\n', '').rstrip('\r', '')所做的,这可能不是其他人在这个帖子上磕磕绊绊.str.rstrip剥离尽可能多的尾随字符,所以像foo\n\n\n这样的字符串会导致foo的误报,而你可能有 在剥离一个尾随线之后想要保留其他换行符。)
Taylor Edmiston answered 2019-03-24T22:32:58Z
3 votes
只需使用:
line = line.rstrip("\n")
要么
line = line.strip("\n")
你不需要任何这些复杂的东西
Help me answered 2019-03-24T22:33:37Z
3 votes
>>> ' spacious '.rstrip()
' spacious'
>>> "AABAA".rstrip("A")
'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
''
>>> "ABCABBA".rstrip("AB")
'ABC'
answered 2019-03-24T22:34:00Z
2 votes
我们通常会遇到三种类型的行结尾:a == b == c,True和\r\n.a == b == c中的一个相当简单的正则表达式,即r"\r?\n?$",能够捕获它们。
(我们必须抓住他们所有人,我是对的吗?)
import re
re.sub(r"\r?\n?$", "", the_text, 1)
使用最后一个参数,我们将出现次数限制为1,在某种程度上模仿chomp。 例:
import re
text_1 = "hellothere\n\n\n"
text_2 = "hellothere\n\n\r"
text_3 = "hellothere\n\n\r\n"
a = re.sub(r"\r?\n?$", "", text_1, 1)
b = re.sub(r"\r?\n?$", "", text_2, 1)
c = re.sub(r"\r?\n?$", "", text_3, 1)
...其中a == b == c是True。
internetional answered 2019-03-24T22:34:54Z
1 votes
如果你担心速度(比如你有一个looong字符串列表)并且你知道换行符char的性质,字符串切片实际上比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
Stephen Miller answered 2019-03-24T22:35:33Z
0 votes
抓住所有:
line = line.rstrip('\r|\n')
user4178860 answered 2019-03-24T22:36:04Z
0 votes
这将适用于Windows和Linux(如果您只寻找重新解决方案,那么re sub有点贵)
import re
if re.search("(\\r|)\\n$", line):
line = re.sub("(\\r|)\\n$", "", line)
Venfah Nazir answered 2019-03-24T22:36:44Z