python strip方法_Python strip()方法

只移除字符串头尾指定的字符,中间部分不会移除:

#!/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 可以重复删除。如果有不正确的地方期待指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值