开始Python -- String处理(2)

5String方法

1 find:返回子串在Sting中第一次出现的index值,没有找到返回-1

>>> title = "Monty Python's Flying Circus"

>>> title.find('Monty')

0

>>> title.find('Python')

6

>>> title.find('Zirquss')

-1

l         可以指定开始查找的位置(包括)和可选的结束位置(不包括)

>>> subject = '$$$ Get rich now!!! $$$'

>>> subject.find('$$$')

0

>>> subject.find('$$$', 1) # Only supplying the start

20

>>> subject.find('!!!')

16

>>> subject.find('!!!', 0, 16) # Supplying start and end

-1

2 join:连接Sequence中的所有元素为一个String,元素必须是String

>>> seq = [1, 2, 3, 4, 5]

>>> '+'.join(seq)

Traceback (most recent call last):

  File "<interactive input>", line 1, in ?

TypeError: sequence item 0: expected string, int found

>>> seq = ['1', '2', '3', '4', '5']

>>> '+'.join(seq)

'1+2+3+4+5'

>>> dirs = '', 'usr', 'bin', 'env'

>>> '/'.join(dirs)

'/usr/bin/env'

>>> print 'C:' + '//'.join(dirs)

C:/usr/bin/env

3 lower:将String转换成小写

>>> 'Trondheim Hammer Dance'.lower()

' trondheim hammer dance'

4 replace:将String中所有出现的某个子串替换成另外一个子串

>>> 'This is a test'.replace('is', 'eez')

'Theez eez a test'

5 split:将String分割成Seqence,不使用分隔符,缺省为空白字符

>>> '1+2+3+4+5'.split('+')

['1', '2', '3', '4', '5']

>>> '/usr/bin/env'.split('/')

['', 'usr', 'bin', 'env']

>>> 'Using the default'.split()

['Using', 'the', 'default']

6 strip:移去String左右的空白字符(缺省)

>>> ' internal whitespace is kept '.strip()

'internal whitespace is kept'

l         可以指定要移去的字符集合

>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')

'SPAM * for * everyone'

7 translate

l         Translate()的功能类似replace(),但translate()只对字符进行处理,效率要比replace()

l         在使用Translate()之前,需要调用string模块中的maketrans()函数创建转换表

l         maketrans()函数有两个参数:长度相同的String,表示用第二个String中的每个字符替换第一个String中相同位置的字符

l         最后将maketrans()函数创建的转换表作为参数,传给translate()方法

>>> from string import maketrans

>>> table = maketrans('cs', 'kz')

>>> 'this is an incredible test'.translate(table)

'thiz iz an inkredible tezt'

l         可以使用可选的参数来指定要删除的字符集合

>>> 'this is an incredible test'.translate(table, ' ')

'thizizaninkredibletezt'

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值