如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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
其他回答
这将完全复制perl的chomp(减去数组上的行为)作为“\n”行终止符:
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)
这将适用于windows和linux(如果您只寻找重新解决方案,那么使用re-sub有点贵)
import re
if re.search("(\\r|)\\n$", line):
line = re.sub("(\\r|)\\n$", "", line)
尝试rstrip()方法(参见文档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 '
除了rstrip(),还有strip()和lstrip()方法。下面是其中三个示例:
>>> 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'
在很多层面上,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'
只需使用:
line = line.rstrip("\n")
or
line = line.strip("\n")
你不需要这些复杂的东西