如何删除尾随的换行符?
尝试使用方法rstrip()
(请参见文档Python 2和Python 3)
>>> 'test string '.rstrip() 'test string'
Python的rstrip()
方法默认会删除所有类型的尾随空格,而不仅仅是像Perl中的chomp
一样的一个换行符。
>>> 'test string '.rstrip() 'test string'
要仅删除换行符:
>>> 'test string '.rstrip(' ') 'test string '
除了rstrip()
方法之外,还有strip()
和lstrip()
方法。以下是它们三个的示例:
>>> s = " abc def " >>> s.strip() 'abc def' >>> s.lstrip() 'abc def ' >>> s.rstrip() ' abc def'