新浪博客

python:str.strip()用法详解

2016-10-03 20:50阅读:
函数原型:
str.strip()
作用:删除字符串头和尾的空格,以及位于头尾的 \t之类等等
eg1:
str = ' A B C \t'
str.strip()后,结果:str = 'A B C'
eg2:
str = '0000000this is string example....wow!!!0000000';
print str.strip( '0' );
结果:this is string example....wow!!!
值得注意的是:
当str.strip()括号内为空的时候,默认删除空白符(包括'', '\r', '\t', ' ')
eg3:
str = 'hello world'
print str.strip( 'hello' )
print str.strip( 'hello' ).strip()
print str.strip( ' heldo ' ).strip() #sentence 1
stt = 'h1h1h2h3h4h'
print stt.strip( 'h1' ) #sentence 2
s = '123459947855aaaadgat134f8sfewewrf7787789879879'
print s.strip( '0123456789' ) #sentence 3
结果:
world
world
wor
2h3h4
aaaadgat134f8sfewewrf
截图如下:
python:str.strip()用法详解
help翻译:
该方法用来去掉首尾的空格和tab。返回一个去掉空格的S字符串的拷贝。如果参数chars不为None有值,那就去掉在chars中出现的所有字符。如果chars是unicode,S在操作之前先转化为unicode eg3来源于风中静行

我的更多文章

下载客户端阅读体验更佳

APP专享