如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
您可以使用line=line.rstrip('\n')。这将从字符串末尾删除所有换行符,而不仅仅是一行。
其他回答
尝试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'
包罗万象:
line = line.rstrip('\r|\n')
去除行尾(EOL)字符的规范方法是使用string 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标准要求结尾“\r”作为其EOL字符。使用此消息的Windows计算机已附加了自己的“\r\n”EOL字符。因此,每行的结尾看起来像“\r\n”。使用rstrip(“\r\n”)会删除整个“\r\n”,这不是我想要的。在这种情况下,我只是把最后两个字符切下来。
注意,与Perl的chomp函数不同,这将去掉字符串末尾的所有指定字符,而不仅仅是一个:
>>> "Hello\n\n\n".rstrip("\n")
"Hello"
特殊情况的解决方案:
如果换行符是最后一个字符(大多数文件输入都是这样),那么对于集合中的任何元素,都可以按如下方式进行索引:
foobar= foobar[:-1]
剪切换行符。
如果你关心速度(比如你有一个很长的字符串列表)并且你知道换行符的性质,那么字符串切片实际上比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