只移除字符串头尾指定的字符,中间部分不会移除:
#!/usr/bin/python
str = "0000000this is string 0000example....wow!!!0000000";
print str.strip( '0' );
输出结果中间部分的 0 还是存在的:
this is string 0000example....wow!!!
像 lstrip 和 rstrip 一样,strip() 也可以带多个字符参数,测试如下:
# -*- coding:utf-8 -*-
str1 = ' iam string '
print "str1:\'%s\'" %str1
print "str1.strip():\'%s\'" %str1.strip()
str2 = '@@@@@iamstring@@@@@'
print "str2:\'%s\'" %str2
print "str2.strip('@'):\'%s\'" %str2.strip('@')
print "str2.strip('@@'):\'%s\'" %str2.strip('@@')
print "str2.strip('@@@@@@'):\'%s\'" %str2.strip('@@@@@@')
print "str2.strip('@i'):\'%s\'" %str2.strip('@i')
print "str2.strip('@ag'):\'%s\'" %str2.strip('@g')
输出结果为:
str1:' iam string '
str1.strip():'iam string'
str2:'@@@@@iamstring@@@@@'
str2.strip('@'):'iamstring'
str2.strip('@@'):'iamstring'
str2.strip('@@@@@@'):'iamstring'
str2.strip('@i'):'amstring'
str2.strip('@ag'):'iamstrin'
从第二个序列看出来好像并不是指定序列:
str = "123abcrunoob321"
print (str.strip( '12' )) # 字符序列为 12 ?
因为输出:
3abcrunoob3
结尾的难不成是从右向左寻找??
带着疑问我测试了几次,发现:
str = "123abcrunoob3221"print (str.strip( '32b1' ))
输出:
abcrunoo
看起来像是参数中每个字符 3 2 b 1 都是独立的,
在开头从左向右依次查找字符,如果是这几个中的一个就删除,继续往下找,若不是,就终止,所以开头保留到a 。
在结尾从右往左查找,同上,而且结尾的 22 可以重复删除。如果有不正确的地方期待指正。