我怎样才能删除尾随的换行符?
- 2024-11-28 08:38:00
- admin 原创
- 221
问题描述:
如果字符串的最后一个字符是换行符,如何删除它?
"abc
" --> "abc"
解决方案 1:
尝试该方法rstrip()
(参见文档Python 2和Python 3)
>>> 'test string
'.rstrip()
'test string'
Python 的rstrip()
方法默认删除所有类型的尾随空格,而不是像 Perl 那样只删除一个换行符chomp
。
>>> 'test string
'.rstrip()
'test string'
仅去除换行符:
>>> 'test string
'.rstrip('
')
'test string
'
除了 之外rstrip()
,还有方法strip()
和lstrip()
。下面是包含这三个方法的示例:
>>> s = "
abc def
"
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def
'
>>> s.rstrip()
'
abc def'
解决方案 2:
并且我会说获取没有尾随换行符的行的“pythonic”方法是 splitlines()。
>>> text = "line 1
line 2
line 3
line 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']
解决方案 3:
删除行尾 (EOL) 字符的规范方法是使用字符串 rstrip() 方法删除任何尾随的 \r 或 \n。以下是 Mac、Windows 和 Unix EOL 字符的示例。
>>> 'Mac EOL
'.rstrip('
')
'Mac EOL'
>>> 'Windows EOL
'.rstrip('
')
'Windows EOL'
>>> 'Unix EOL
'.rstrip('
')
'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
".rstrip("
")
"Hello"
解决方案 4:
请注意,rstrip 的作用与 Perl 的 chomp() 并不完全相同,因为它不会修改字符串。也就是说,在 Perl 中:
$x="a
";
chomp $x
结果$x
是"a"
。
但在 Python 中:
x="a
"
x.rstrip()
意味着 的值x
仍为。即使 也并不总是给出相同的结果,因为它 会从字符串末尾删除所有空格,而不仅仅是最多一个换行符。`"a
"`x=x.rstrip()
解决方案 5:
我可能会使用这样的东西:
import os
s = s.rstrip(os.linesep)
我认为 的问题在于`rstrip("
"),您可能需要确保行分隔符是可移植的。(据说有些过时的系统使用
"
")。另一个问题是
rstrip会删除重复的空格。希望
os.linesep`会包含正确的字符。上面的方法对我有用。
解决方案 6:
您可以使用`line = line.rstrip('
')`。这将删除字符串末尾的所有换行符,而不仅仅是一个。
解决方案 7:
s = s.rstrip()
将删除字符串末尾的所有换行符s
。需要赋值,因为rstrip
返回一个新字符串而不是修改原始字符串。
解决方案 8:
"line 1
line 2
...".replace('
', '').replace('
', '')
>>> 'line 1line 2...'
或者你也可以通过正则表达式变得更加极客
解决方案 9:
这将精确复制 perl 的 chomp(数组上的减法行为)的“\n”行终止符:
def chomp(x):
if x.endswith("
"): return x[:-2]
if x.endswith("
") or x.endswith("
"): return x[:-1]
return x
(注意:它不会“就地”修改字符串;它不会删除多余的尾随空格;考虑到 \r\n)
解决方案 10:
您可以使用条带:
line = line.strip()
演示:
>>> "
hello world
".strip()
'hello world'
解决方案 11:
rstrip 在很多层面上都与 chomp 的功能不同。阅读http://perldoc.perl.org/functions/chomp.html你会发现 chomp 确实非常复杂。
然而,我的主要观点是 chomp 最多删除 1 个行结尾,而 rstrip 会删除尽可能多的行结尾。
在这里你可以看到 rstrip 删除了所有换行符:
>>> 'foo
'.rstrip(os.linesep)
'foo'
使用 re.sub 可以实现更接近典型的 Perl chomp 用法,如下所示:
>>> re.sub(os.linesep + r'Z','','foo
')
'foo
'
解决方案 12:
小心使用"foo".rstrip(os.linesep)
:这将仅针对执行 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
".rstrip(os.linesep)
'foo
'
>>>
`"foo".rstrip("
")`按照 Mike 上面说的,改用。
解决方案 13:
Python 文档中的一个示例只是使用了line.strip()
。
Perl 的chomp
函数仅在字符串末尾确实存在换行符序列时才将其删除。
这是我计划在 Python 中执行此操作的方法,process
从概念上讲,if 是我需要的函数,以便对此文件中的每一行执行有用的操作:
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)
解决方案 14:
import re
r_unwanted = re.compile("[
]")
r_unwanted.sub("", your_text)
解决方案 15:
我不会使用 Python 编程,但是我在 python.org 上看到一个常见问题解答,其中提倡在 python 2.2 或更高版本中使用 S.rstrip("\r\n")。
解决方案 16:
如果你的问题是清理多行 str 对象(oldstr)中的所有换行符,你可以按照分隔符 '\n' 将其拆分为一个列表,然后将此列表连接成一个新的 str(newstr)。
`newstr = "".join(oldstr.split('
'))`
解决方案 17:
我发现能够通过迭代器获取已截断的行非常方便,这与从文件对象获取未截断的行的方式类似。您可以使用以下代码来实现:
def chomped_lines(it):
return map(operator.methodcaller('rstrip', '
'), it)
使用示例:
with open("file.txt") as infile:
for line in chomped_lines(infile):
process(line)
解决方案 18:
我正在将之前在另一个答案的评论中发布的基于正则表达式的答案冒泡出来。我认为使用re
比 更清楚、更明确地解决此问题str.rstrip
。
>>> import re
如果要删除一个或多个尾随换行符:
>>> re.sub(r'[
]+$', '', '
x
')
'
x'
如果要删除所有地方的换行符(不只是尾随的换行符):
>>> re.sub(r'[
]+', '', '
x
')
'x'
如果您只想删除 1-2 个`尾随换行符(即
,,,,,,,)
``
``
``
`
>>> re.sub(r'[
]{1,2}$', '', '
x
')
'
x
'
>>> re.sub(r'[
]{1,2}$', '', '
x
')
'
x
'
>>> re.sub(r'[
]{1,2}$', '', '
x
')
'
x'
我感觉大多数人真正想要的是只删除一个尾随换行符,`或者
`仅此而已。
>>> re.sub(r'(?:
|
)$', '', '
x
', count=1)
'
x
'
>>> re.sub(r'(?:
|
)$', '', '
x
', count=1)
'
x
'
>>> re.sub(r'(?:
|
)$', '', '
x
', count=1)
'
x'
>>> re.sub(r'(?:
|
)$', '', '
x
', count=1)
'
x'
(这?:
是创建一个非捕获组。)
(顺便说一下,这不是其他`'...'.rstrip('
', '').rstrip('
', '')人可能不清楚的功能。 删除
str.rstrip尽可能多的尾随字符,因此像这样的字符串
foo
会导致误报,
foo`而您可能希望在删除单个尾随字符后保留其他换行符。)
解决方案 19:
特殊情况的解决方法:
如果换行符是最后一个字符(大多数文件输入的情况都是如此),那么对于集合中的任何元素,您都可以按如下方式进行索引:
foobar= foobar[:-1]
切出你的换行符。
解决方案 20:
看起来没有一个可以完美模拟 perl 的chomp的函数。特别是,rstrip无法处理像 这样的多字符换行符分隔符`。但是,正如这里指出的那样,splitlines可以做到。按照我对另一个问题的回答,您可以结合使用join和splitlines来从字符串中删除/替换所有换行符:
s`
''.join(s.splitlines())
下面的代码会删除一个尾随换行符(我相信 chomp 也会这么做)。True
作为keepends
参数传递给 splitlines 会保留分隔符。然后,再次调用 splitlines 以删除最后一个“行”上的分隔符:
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''
解决方案 21:
s = '''Hello World
Hi 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
Hi '''
print(re.sub(r"s+", "", s), sep='') # s matches all white spaces
>HelloWorldHi
替换 \n、\t、\r
s.replace('
', '').replace(' ','').replace('
','')
>' Hello World Hi '
使用正则表达式
s = '''Hello World
Hi There'''
regex = re.compile(r'[
]')
regex.sub("", s)
>'Hello World Hi There'
与 Join
s = '''Hello World
Hi There'''
' '.join(s.split())
>'Hello World Hi There'
解决方案 22:
>>> ' spacious '.rstrip()
' spacious'
>>> "AABAA".rstrip("A")
'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
''
>>> "ABCABBA".rstrip("AB")
'ABC'
解决方案 23:
只需使用:
line = line.rstrip("
")
或者
line = line.strip("
")
你不需要这些复杂的东西
解决方案 24:
我们通常会遇到三种类型的行尾:`、
和
。 一个相当简单的正则表达式
re.sub,即
r"
?
?$"`,能够捕获所有这些行尾。
(我们必须把它们全部抓住,对吗?)
import re
re.sub(r"
?
?$", "", the_text, 1)
使用最后一个参数,我们将替换的次数限制为 1,在某种程度上模仿 chomp。例如:
import re
text_1 = "hellothere
"
text_2 = "hellothere
"
text_3 = "hellothere
"
a = re.sub(r"
?
?$", "", text_1, 1)
b = re.sub(r"
?
?$", "", text_2, 1)
c = re.sub(r"
?
?$", "", text_3, 1)
... 在a == b == c
哪里True
。
解决方案 25:
如果您关心速度(假设您有一个很长的字符串列表)并且您知道换行符的性质,那么字符串切片实际上比 rstrip 更快。下面是一个小测试来说明这一点:
import time
loops = 50000000
def method1(loops=loops):
test_string = 'num
'
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
'
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
解决方案 26:
这适用于 Windows 和 Linux(如果你只寻求重新解决方案,那么使用重新订阅会有点贵)
import re
if re.search("(\\r|)\\n$", line):
line = re.sub("(\\r|)\\n$", "", line)
解决方案 27:
总而言之:
line = line.rstrip('
|
')
解决方案 28:
怎么样:
line = line.rstrip('
*
')