前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python str.strip()函数

Python str.strip()函数

作者头像
py3study
发布2020-01-15 17:35:47
8490
发布2020-01-15 17:35:47
举报
文章被收录于专栏:python3

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

string.strip(s[, chars])

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

如果chars被忽略或者是None,空白字符串被移除。如果chars不是None并存在,在字符串的头尾的chars都将被移除。

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

下面例子中字符以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')+'*'

结果输出:

*aaaaahhaaaaaaahH*

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/06/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档