python怎么去掉换行符_如何在Python中删除尾部换行符?
如何在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
總結
以上是生活随笔為你收集整理的python怎么去掉换行符_如何在Python中删除尾部换行符?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux编码指令大全,Linux指令篇
- 下一篇: PH值算法