跟我一起学Python之九:字符串常用方法
来源:互联网 发布:期货数据库 编辑:程序博客网 时间:2024/05/16 06:14
1.find
从一个字符串中,查找另一个子字符串,然后返回它的位置。
>>> 'With a moo-moo here,and a moo-moo'.find ('moo')7
返回最左端的索引,如果没有找到返回-1。
>>> title="Monty Python's Flying Circus">>> title.find("Monty")0>>> title.find("yumeng")-1
注意:find区分大小写
>>> subiect='$$$ Get rich now!!! $$$'>>> subiect.find('$$$')0>>> subiect.find('$$$',4)20
4作为起始索引。
>>> subiect.find('$$$',4,16)-1
4,16是此次find的索引范围。
2.join
用于连接字符串。
字符串特征单引号包围。
列表特征中括号包围。
元组特征小括号包围。
>>> seq=['1','2','3','4','5']>>> sep='+'>>> import string>>> sep.join(seq)'1+2+3+4+5'>>> dirs='','usr','bin','python'>>> '/'.join(dirs)'/usr/bin/python'>>> print 'C:'+'\\'.join(dirs)C:\usr\bin\python
3.lower
用于转换大小写字母。
>>> 'Trondheim Hammer Dance'.lower()'trondheim hammer dance'>>> if 'Gumby' in ['gumby','smith','jones']:print "Found it!">>> if 'Gumby'.lower() in ['gumby','smith','jones']:print "Found it!"Found it!
4.replace
替换函数
>>> 'This is a test'.replace('is','eez')'Theez eez a test'
格式:对象.replace(old,new)
5.split
分割函数
>>> '1+2+3+4+5'.split('+')['1', '2', '3', '4', '5']
split不跟参数默认为空格分隔符。
>>> 'using the default'.split()['using', 'the', 'default']
6.strip
删除两边没有必要的空格
>>> ' internal whitespace is keps '.strip()'internal whitespace is keps'中间空格不会删除>>> names = ['gumby','smith','jones']>>> name = 'gumby '>>> if name in names:print 'Found it!'>>> if name.strip() in names:print 'Found it!'Found it!>>>
可指定删除字符
>>> '*** SPAM * for * everyone !!! ***'.strip(' *!')'SPAM * for * everyone'
7.translate
用于替换
translate只处理单个字符替换
创建转换表
>>> from string import maketrans>>> table=maketrans('cs','kz') c->k s->z
引用转换表进行替换
>>> 'this is an incredible test'.translate(table)'thiz iz an inkredible tezt'
可加参数删除特定字符
>>> 'this is an incredible test'.translate(table,' ')'thizizaninkredibletezt'>>> 'this is an incredible test'.translate(table,'test')'hi i an inkrdibl '
- 跟我一起学Python之九:字符串常用方法
- 跟我一起学Python之四:字符串简介
- 跟我一起学Python之十一:字典方法
- 跟我一起学Python之八:基本字符串和字符串格式化
- 跟我一起学Python之五:序列
- 跟我一起学Python之六:列表
- 跟我一起学Python之七:元组
- 跟我一起学Python之十:字典
- 跟我一起学python(九),网络编程(进阶篇)
- 跟我一起学C++之重载
- 学习笔记九:跟我一起学makefile
- 跟我学aspectj之九----- advice
- 跟我一起学python(一),python基础
- 跟我一起学python(二),python基本数据类型
- 跟我一起学python(四),python的模块
- 跟我一起学Python之二:变量语句及函数简介
- 跟我一起学Python之三:模块及保存运行
- 跟我一起学Python之一:数字和表达式
- 两篇很牛的vim使用技巧
- linux内核内存管理学习之一(基本概念,分页及初始化)
- PhysicsEditor的应用
- C++获取系统图标方法
- 后缀自动机学习资料
- 跟我一起学Python之九:字符串常用方法
- java 打印表格文件
- [HDU 4336]Card Collection[状态压缩DP][概率DP][容斥原理]
- HDU 4666 Hyperspace
- WinXP硬盘安装Ubuntu 11.10双系统全程图解
- Java主类结构
- Power Strings(poj2406 ,简单KMP)
- dsPIC33F之Latched Fault Code Workaround via PWM Override Logic Routine
- 两个ViewController间传值(二)