如何删除尾随的换行符? [英] How can I remove a trailing newline?

查看:30
本文介绍了如何删除尾随的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 的 chomp 函数的 Python 等价物是什么,如果字符串是换行符,它会删除字符串的最后一个字符?

解决方案

尝试方法 rstrip()(参见文档 Python 2Python 3)

<预><代码>>>>'测试字符串 '.rstrip()'测试字符串'

Python 的 rstrip() 方法默认删除所有类型的尾随空格,而不仅仅是 Perl 对 chomp.

<预><代码>>>>'测试字符串 '.rstrip()'测试字符串'

仅去除换行符:

<预><代码>>>>'测试字符串 '.rstrip(' ')'测试字符串 '

除了rstrip(),还有方法strip()lstrip().这是其中三个的示例:

<预><代码>>>>s = " abc def ">>>s.strip()'abc def'>>>s.lstrip()'abc def '>>>s.rstrip()' abc def'

What is the Python equivalent of Perl's chomp function, which removes the last character of a string if it is a newline?

解决方案

Try the method rstrip() (see doc Python 2 and Python 3)

>>> 'test string
'.rstrip()
'test string'

Python's rstrip() method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp.

>>> 'test string 
 


 

'.rstrip()
'test string'

To strip only newlines:

>>> 'test string 
 


 

'.rstrip('
')
'test string 
 


 '

In addition to rstrip(), there are also the methods strip() and lstrip(). Here is an example with the three of them:

>>> s = "   

  
  abc   def 

  
  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def 

  
  '
>>> s.rstrip()
'   

  
  abc   def'

这篇关于如何删除尾随的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆