python学习笔记(四)字符串函数一

原文链接:http://blog.svenapps.com/post/python-xue-xi-bi-ji/python-xue-xi-bi-ji-si-zi-fu-chuan-han-shu-yi#content

注:本资料是个人学习笔记,仅供参考

1.join()/split()

   join(),把集合中所有的字符串按照指定的分隔符连接起来,注意:join连接的列表里面的元素必须都是字符串
   split(),把字符串,按照指定分隔符拆分称集合
     phoneName = ['iPhone','Android','Meego']
     print '>'.join(phoneName)
     phoneStr = 'iPhone,Android,Meego'
     print  phoneStr.split()
     #结果iPhone>Android>Meego
     #      ['iPhone,Android,Meego']
2.strip()
     Python中的strip用于去除字符串的首尾字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。
     这三个函数都可传入一个参数,指定要去除的首尾字符。
     需要注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如:
 
     theString = 'saaaay yes no yaaaass'
     print theString.strip('say')
     theString依次被去除首尾在['s','a','y']数组内的字符,直到字符在不数组内。所以,输出的结果为:
     yes no
     比较简单吧,lstrip和rstrip原理是一样的。
 
     注意:当没有传入参数时,是默认去除首尾空格的。
 
     theString = 'saaaay yes no yaaaass'
     print theString.strip('say')
     print theString.strip('say ') #say后面有空格
     print theString.lstrip('say')
     print theString.rstrip('say')
     运行结果:
 
     yes no
     es no
     yes no yaaaass
     saaaay yes no
3.starswith()/endswith()判断文字是否以字符开头或者结尾
     strs ='iPhone'
     print strs.startswith('iP') 
     print strs.startswith('P',1) #下标为1的位置是否P
     print strs.startswith('one',3,6)#从序列下标3的位置开始,到6结束,不包含6,比较,序列从0开始
     print strs.endswith('ne')
     print strs.endswith('e',5)
     print strs.endswith('one',3,6)
4.find()/rfind()
   查找字符串中第一次出现相同字符的的下标,注:空格也是一个字符
    find()从左边查找,rfind()从右边查找
5.replace()替换字符串
   strs.replace('c','C',2)替换字符串前2个字符‘c' 
posted @ 2013-05-08 17:46  七夜小魔军  阅读(197)  评论(0编辑  收藏  举报