如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
小心使用“foo”.rstrip(os.lineep):这只会在执行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”),如Mike所述。
其他回答
我们通常会遇到三种类型的行尾:\n、\r\n和\r\n。re.sub中的一个相当简单的正则表达式,即r“\r?\n?$”,能够将它们全部捕获。
(我们必须抓住他们,对吗?)
import re
re.sub(r"\r?\n?$", "", the_text, 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。
在很多层面上,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'
如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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
我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。
我发现,通过迭代器获取压缩行很方便,与从文件对象获取未压缩行的方式类似。您可以使用以下代码执行此操作:
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)