Python 字符串操作(替换、删除、截取、复制、连接等)
上一篇 /
下一篇 2013-05-20 10:54:17
/ 个人分类:Python
去空格及特殊符号
51Testing软件测试网;Y\^PT^Python中的strip用于去除字符串的首尾字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。51Testing软件测试网$g]/x+k*m
51Testing软件测试网D#X$np-Y4cD这三个函数都可传入一个参数,指定要去除的首尾字符。51Testing软件测试网S)qq(tf'm
s.strip().lstrip().rstrip(',')
theString = 'saaaay yes no yaaaass'
print theString.strip( 'say' )
|
51Testing软件测试网N6b'F*catheString依次被去除首尾在['s','a','y']数组内的字符,直到字符不在数组内。所以,输出的结果为:
\ P
l
n#Be!Dau0yes no 51Testing软件测试网2c%}V;J_aU r
比较简单吧,lstrip和rstrip原理是一样的。51Testing软件测试网v-t\}6jhV
51Testing软件测试网0YA\8\gOWM*g注意:当没有传入参数时,是默认去除首尾空格的。 51Testing软件测试网~(c9T
E tq0?9a
theString = ' saaaay yes no yaaaass ' :Y"T,g s bjL0withoutFrontEndSpaceString = theString.strip().lstrip().rstrip(','); #去首位空格,右去逗号。 5/20/2013 11:44:05 AM bC3HMG2YHN0print withoutFrontEndSpaceString; #saaaay yes no yaaaass :}*|(N+C%nGj0print withoutFrontEndSpaceString.strip('say'); #withoutFrontEndSpaceString依次被去除首尾在['s','a','y']数组内的字符,直到字符不在数组内。 #hL,|7?`Y0print withoutFrontEndSpaceString.strip('say ') #say后面有空格 [.^5@Ep/K0print withoutFrontEndSpaceString.lstrip('say')51Testing软件测试网.J'k$q9\)hA print withoutFrontEndSpaceString.rstrip('say')
|
51Testing软件测试网DpMVN2Qhp*[/v运行结果:
U*@#`K"v]$iv051Testing软件测试网k(v?)p{saaaay yes no yaaaass51Testing软件测试网6m$o&o
WI"j6w
yes no
&i6Vd?{o0es no
%~2CKb@fD0 yes no yaaaass51Testing软件测试网$a ~`T3DY]+a3h!Ef
saaaay yes no
4uD8K5]2CK051Testing软件测试网Ku Rlz}|V7bT0_
Lu;L@sS&d051Testing软件测试网2M@t)x+L格式化输出---- %s; %d; %x; %o; %f;51Testing软件测试网2LE ] H7dU$n$sl
strHello = "the length of (%s) is %d" %('Hello World', len('Hello World'))
8|9\AL!P ~+m*L
D$nV0print strHello
2C2TzR6i|_+bW|051Testing软件测试网Z)p8jL2`8P,WDM"A