python 字符处理

一. 字符串的表示
      用单引号或双引号构成字符串。
      “abc” \
      ‘def’
      表示一个字符串,而“abc”+“def”是两个字符串连接在一起,两者不一样。
     ““”    “”“中间可以为任意长的字符串
二.字符串操作
      1.大小写转换
         s.capitalize()  #字符串s首写字母大写
         s.lower()  #全部变成小写
         s.upper() #全部变成大写
         s.swapcase()  #大小写互换
         len(s)  #得到字符串的大小
      2.查找子串
         s.find(substring,[start[,end]])     找到,返回索引值,找不到,返还-1
         s.rfind(substring,[start[,end]])      反向查找
         s.index(substring,[start[,end]])     与find()类似,如果找不到substring,就产生一个
                                                                  ValueError的异常
         s.rindex(substring,[start[,end]])      反向查找
         s.count(substring,[start[,end]])       返回找到substring的次数
     3.格式化字符串
        用法  s% <tuple>      tuple表示一个参数列表,把tuple中的每一个值用字符串表示,表示的格                                            式有s来确定。
                  s.ljust(width)   左对齐,如果width比len(s)大,则后面补空格。否则返回s。
                  s.rjust(width)   右对齐    
                  s.center(width)  居中
                  s.lstrip()    去掉左边的空白字符
                  s.rstrip()   去掉右边的空白字符  
                  s.lstrip()    去掉两边的空白字符
   4. 字符串的合并和分解
       合并:s.join(words)
                   words是一个含有字符串的tuple或list。join用s作为分隔符将words中的字符串连接起                   来,合并为一个字符串。
                    例:>>> “+”.join([”hello”,”my”,”friedn”])
                            ‘hello+my+friedn’
       分解:s.split(words)
                   words是一个字符串,表示分隔符。split的操作和join相反。将s分解为一个list。 
                   例:>>> “hello my fried”.split(” “)
                           [’hello’, ‘my’, ‘fried’]   

posted @ 2009-11-13 18:20  Neo.Yan  阅读(550)  评论(0编辑  收藏  举报