码迷,mamicode.com
首页 > 编程语言 > 详细

python的string.strip(s[, chars])方法的各种小细节

时间:2015-02-21 06:34:05      阅读:579      评论:0      收藏:0      [点我收藏+]

标签:

下面的英文说明是官方给出:

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.

下面例子中字符以tab抬头,以空格结尾。

line=‘    hello happybks! ‘

print ‘*‘+line.strip()+‘*‘
print ‘*‘+line.strip(‘ ‘)+‘*‘
print ‘*‘+line.strip(‘    ‘)+‘*‘
print ‘*‘+line.strip(‘h‘)+‘*‘

输出结果如下:

*hello happybks!*
*hello happybks!*
*hello happybks!*
*    hello happybks! *

可以发现不传参数,则会把字符串开头和结尾的空格、tab全部删除,中间的空格和tab不会

传空格或者tab参数,子串传仍然会把字符串开头和结尾的无论空格还是tab都一并删除

当传入的参数是其他参数时,字符串开头结尾不是该参数字符串,则没有任何效果

但是如果字符串的开头和结尾是其他字符串,并且传入的参数也是这个字符串,那么会将字符串开头和结尾的参数串全部清掉,无论有多少个。但是区分大小写。

例如,下面的例子:

line2=‘haaaaahhaaaaaaahHhhh‘
print ‘*‘+line2.strip(‘h‘)+‘*‘


python的string.strip(s[, chars])方法的各种小细节

标签:

原文地址:http://my.oschina.net/u/1156339/blog/379428

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!