首页 / PYTHON / Python strip()方法
Python strip()方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python strip()方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2371字,纯文字阅读大概需要4分钟。
内容图文
![Python strip()方法](/upload/InfoBanner/zyjiaocheng/608/cc269d8c75be4b60a964a40393fdf05d.jpg)
描述
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
语法
strip()方法语法:
1 |
str .strip([chars]);
|
参数
- chars -- 移除字符串头尾指定的字符序列。
返回值
返回移除字符串头尾指定的字符生成的新字符串。
实例
以下实例展示了strip()函数的使用方法:
1 |
实例(Python? 2.0 + )
|
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
?
str = "00000003210Runoob01230000000" ;
print str .strip(? '0' );?? # 去除首尾字符 0
?
?
str2? = "?? Runoob????? " ;??? # 去除首尾空格
print str2.strip();
|
以上实例输出结果如下:
1 2 |
3210Runoob0123
Runoob
|
从结果上看,可以注意到中间部分的字符并未删除。
以上下例演示了只要头尾包含有指定字符序列中的字符就删除:
实例
1 2 3 4 5 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
?
str = "123abcrunoob321"
print ( str .strip(? '12' ))?? # 字符序列为 12
|
以上实例输出结果如下:
1 |
3abcrunoob3
|
3 篇笔记 写笔记
- 只移除字符串头尾指定的字符,中间部分不会移除:
1 2 3 4 |
#!/usr/bin/python
str = "0000000this is string 0000example....wow!!!0000000" ;
print str .strip(? '0' );
|
输出结果中间部分的 0 还是存在的:
1 |
this? is string? 0000example ....wow!!!
|
- 像 lstrip 和 rstrip 一样,strip() 也可以带多个字符参数,测试如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# -*- 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')
|
输出结果为:
1 2 3 4 5 6 7 8 |
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'
|
- 从第二个序列看出来好像并不是指定序列:
1 2 |
str = "123abcrunoob321"
print ( str .strip(? '12' ))? # 字符序列为 12 ?
|
因为输出:
1 |
3abcrunoob3
|
结尾的难不成是从右向左寻找??
带着疑问我测试了几次,发现:
1 |
str = "123abcrunoob3221" print ( str .strip(? '32b1' ))
|
输出:
1 |
abcrunoo
|
看起来像是参数中每个字符 3 2 b 1 都是独立的,
在开头从左向右依次查找字符,如果是这几个中的一个就删除,继续往下找,若不是,就终止,所以开头保留到a 。
在结尾从右往左查找,同上,而且结尾的 22 可以重复删除。如果有不正确的地方期待指正。
内容总结
以上是互联网集市为您收集整理的Python strip()方法全部内容,希望文章能够帮你解决Python strip()方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。