python中的strip用法

python中提供了三个函数.strip([chars])、.lstrip([chars])、.rstrip([chars])用于去除字符串的左右空格/n,制表符/t,或者指定字符,这对于提取用户输入内容时非常友好,在处理用户误输入的空格,制表符等方面,显得更加直观优雅。但是还是有新手容易弄错其中细微区别,以下我把自己理解的整理下,希望能帮助到那些正在学习python童鞋们

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

当然,如果要去掉指定的字符也是可以的,chars可以是你要去掉的字符

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

有些童鞋肯定用hello world做过例子,试了一下去除多个字符的效果

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

想象中的结果应该是‘lo world’才对呀?!
其实这个在python官方文档中是有说明的,如下
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:
着重看最后一句,这个要去除的值的所有组合都会被去掉,简单的说就是并不是仅仅去除“hello world”中前面的三个字符“hel”,而是去掉"hel"字符的所有组合,即从两边开始,只要有出现[h,e,l]这三个字符中的一个,就会去掉并再从头查找,一直到两边没有[h,e,l]中的任何一个为止。

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

上面这个例子可以很好的看出,H之间的abc没有被去掉,其他的各种组合被都去掉了
ps:.lstrip([chars]) 的左边去除方式和 .rstrip([chars]) 的右边的去除方式同上
希望童鞋们在以后使用过程中要留心指定字符串的去除,有可能和预想的不一样哦
有不懂的可以去官方文档查看,标准且详尽,人生苦短,我用python!!!

猜你喜欢

转载自blog.csdn.net/weixin_41897122/article/details/101572995