跟我一起学Python之九:字符串常用方法

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 '
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值