如何删除尾随换行符? [英] How can I remove a trailing newline?
本文介绍了如何删除尾随换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Perl的chomp
函数与Python等效吗?如果是换行符,它将删除字符串的最后一个字符?
What is the Python equivalent of Perl's chomp
function, which removes the last character of a string if it is a newline?
推荐答案
尝试方法rstrip()
(请参阅doc Python 3 )
Try the method rstrip()
(see doc Python 2 and Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python的rstrip()
方法默认情况下会剥离所有种尾随空格,而不仅仅是Perl使用
Python's rstrip()
method strips all kinds of trailing whitespace by default, not just one newline as Perl does with 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 '
还有方法lstrip()
和strip()
:
>>> 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'
这篇关于如何删除尾随换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文