Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

python - 如何删除尾随换行符?(How can I remove a trailing newline?)

Perl的chomp函数在Python中的等效功能是什么,如果是换行符,它将删除字符串的最后一个字符?

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...