Skip to content

Latest commit

 

History

History
31 lines (21 loc) · 781 Bytes

112.md

File metadata and controls

31 lines (21 loc) · 781 Bytes

#如何删除Python中的换行符?

原问题地址: http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python

##问题:

在Python中,什么是与Perl 的chomp 功能相对应,用于消除某个值的最后一个字符?

回答:

尝试rstrip方法。

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

注意Python中的rstrip方法是以默认的方式除去各种尾部空格,而不只是像Perl中的chomp那样除去换行符。为了达到只除去换行符的目的:

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

你还可以使用lstrip和strip方法。

>>> s = " \n  abc   def   "
>>> s.strip()
'abc   def'
>>> s.rstrip()
' \n  abc   def'
>>> s.lstrip()
'abc   def   '
>>>