如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
包罗万象:
line = line.rstrip('\r|\n')
其他回答
s = s.rstrip()
将删除字符串s末尾的所有换行符。需要赋值,因为rstrip返回一个新字符串,而不是修改原始字符串。
注意,rstrip的行为与Perl的chomp()不同,因为它不会修改字符串。也就是说,在Perl中:
$x="a\n";
chomp $x
结果$x为“a”。
但在Python中:
x="a\n"
x.rstrip()
将意味着x的值仍然是“a \n”。即使x=x.rstrip()也不总是给出相同的结果,因为它会从字符串末尾删除所有空格,而不是最多一个换行符。
小心使用“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所述。
如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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,似乎没有完美的模拟。特别是,rstrip不能处理像\r\n这样的多字符换行符。然而,分裂线确实如这里所指出的那样。根据我对另一个问题的回答,您可以组合连接和拆分线来删除/替换字符串中的所有换行符:
''.join(s.splitlines())
下面只删除了一个尾随换行符(我相信chomp会这样做)。将True作为keeponds参数传递给拆分线将保留分隔符。然后,再次调用拆分线以删除最后一行上的分隔符:
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''