如何删除尾随的换行符?

23 浏览
0 Comments

如何删除尾随的换行符?

如果字符串的最后一个字符是换行符,如何删除它?

"abc
"  -->  "abc"

admin 更改状态以发布 2023年5月20日
0
0 Comments

我会说获取没有尾随换行符的行的“Pythonic”方式是使用splitlines()方法。

>>> text = "line 1
line 2
line 3
line 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

0
0 Comments

尝试使用方法rstrip()(请参见文档Python 2Python 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'

0