打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
开始Python -- String处理(2) - Dynamic Script Lang...
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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
古代年龄的雅称
2小时超长BBC自然纪录片,中英文双语字幕
征文展示|五年级金奖习作:(  )即景
摄影:具有灵性的鸟儿----【孔雀-2】
摄影:2023年北京见闻【6】
常用标准草书3500字,全本大图共298页( 上 )
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服