Perl的chomp
函数在Python中的等效功能是什么,如果是换行符,它将删除字符串的最后一个字符?
Try the method rstrip()
(see doc Python 2 and Python 3 )
(尝试使用rstrip()
方法(请参阅doc Python 2和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
.
(Python的rstrip()
方法默认情况下会剥离所有尾随空格,而不仅仅是Perl使用chomp
换行。)
>>> 'test string
'.rstrip()
'test string'
To strip only newlines:
(要只删除换行符:)
>>> 'test string
'.rstrip('
')
'test string
'
There are also the methods lstrip()
and strip()
:
(还有方法lstrip()
和strip()
:)
>>> s = "
abc def
"
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def
'
>>> s.rstrip()
'
abc def'