跟我一起学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 '