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

Categories

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

  ask by translate from so

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

1 Answer

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...