Strip usage in python

Three functions are provided in python. Strip( [chars] ), .lstrip( [chars] ), .rstrip( [chars] ) are used to remove left and right spaces /n, tabs /t, or specified characters in a string , This is very friendly for extracting user input content, and it is more intuitive and elegant in handling user mistyped spaces, tabs, etc. However, there are still novices who are easy to mistake the nuances. I will sort out my understanding below, hoping to help those who are learning python children's shoes

>>> str = " hello world         "
>>> str.strip() # 默认去掉左右的所有空格和制表符
'hello world'
>>> str.rstrip()# 默认去掉右边的所有空格和制表符
' hello world'
>>> str.lstrip()# 默认去掉左边的所有空格和制表符
'hello world		'

Of course, if you want to remove the specified characters, chars can be the characters you want to remove

>>> str1 = "aabhello worldbaa"
>>> str1.strip("a")  # 去掉了左右的a
'bhello worldb'
>>> str1.lstrip("a")  # 去掉了左边的a
'bhello worldbaa'
>>> str1.rstrip("a")  # 去掉了右边的a
'aabhello worldb'

Some children’s shoes must have used hello world as examples, and tried to remove multiple characters.

>>> str2= "hello world"
>>> str2.strip("hel")
'o world'

The imaginary result should be'lo world', right? !
In fact, this is explained in the official python documentation, as follows
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values ​​are stripped :
Focus on the last sentence, all combinations of the values to be removed will be removed, in short, it is not just removing The first three characters "hel" in "hello world", but remove all combinations of "hel" characters, that is, starting from both sides, as long as there is one of the three characters [h,e,l], it will Remove and search again from the beginning until there is no one of [h,e,l] on either side.

>>> str3 = "abcHabcHbbcbabcaccabbaaa"
>>> str3.strip("abc")
'HabcH'

The above example can be seen very well, the abc between H has not been removed, other various combinations have been removed
ps: .lstrip ([chars]) left removal method and .rstrip ([chars]) The removal method on the right is the same as above.
I hope that children’s shoes should pay attention to the removal of the specified string in the future use. It may be different from what you expected. If you don’t
understand, you can check the official document. Standard and detailed, life is short, I use python ! ! !

Guess you like

Origin blog.csdn.net/weixin_41897122/article/details/101572995