分享

开始Python -- String处理(2) - Dynamic Script Lang...

 Jamin 2009-12-18
5、String方法
(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'
 
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ruby_beginner/archive/2007/10/11/1820109.aspx

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章