2016.07.09-10 字符串方法

字符串(str)
    
    unicode序列
    字符串是不可变的

    字符串的定义:支持下标操作,支持切片操作,支持解包、封包操作。
        s = 'magedu'
    

    字符串的方法:
        字符串连接:
            join:
                join(...)
                    S.join(iterable) -> str
                    
                使用S拼接一个可迭代对象的每个字符元素(只能拼接字符元素),返回一个字符串,S为一个连接符。
                >>> lst = ['I', 'Love', 'You']    
                >>> ' '.join(lst)    #使用空格拼接字符串
                'I Love You'
                >>> ','.join(lst)    #使用','拼接字符串
                'I,Love,You'
                >>> 
            
        字符串分割:
            split:
                split(...) method of builtins.str instance
                        S.split(sep=None, maxsplit=-1) -> list of strings
                从左到右,通过分隔符进行分隔,sep为分隔符,默认为' ',分割符可以是单个字符,也可以是字符串,但不能是正则表达式,可以使用指定分隔符,对字符串进行分隔,第二个参数为分隔次数,-1(默认值)为分隔所有。        
                
                >>> s
                'my name is ZJ'
                >>> s.split()
                ['my', 'name', 'is', 'ZJ']
                >>> s.split(' ',1)
                ['my', 'name is ZJ']
                >>> s.split(' ',2)
                ['my', 'name', 'is ZJ']
                >>> s.split(' ',-1)
                ['my', 'name', 'is', 'ZJ']

                >>> f = open('/etc/passwd','r')
                >>> a = f.readlines()
                >>> for i in a:
                ...     UserName, *_, bash = i.split(':')
                ...     print(UserName,bash)
                ... 
                root /bin/bash

                bin /sbin/nologin

                daemon /sbin/nologin

                adm /sbin/nologin

                lp /sbin/nologin

            

            rsplit:            
                rsplit(...) method of builtins.str instance
                    S.rsplit(sep=None, maxsplit=-1) -> list of strings
                    
                跟split方法类似,但是rsplit从右到左,通过分隔符进行分隔,sep为分隔符,默认为' ',可以使用指定分隔符,对字符串进行分隔,第二个参数为分隔次数,-1(默认值)为分隔所有。
                
                >>> s
                'my name is ZJ'
                >>> s.rsplit()
                ['my', 'name', 'is', 'ZJ']
                >>> s.rs
                s.rsplit(  s.rstrip(  
                >>> s.rsplit(' ', 1)
                ['my name is', 'ZJ']
                >>> s.rsplit(' ', 2)
                ['my name', 'is', 'ZJ']
                >>> s.rsplit(' ', -1)
                ['my', 'name', 'is', 'ZJ']
                >>> *_, name = s.rsplit(' ', 1) 
                >>> name
                'ZJ'
                >>> 

            splitlines:
                splitlines(...)
                    S.splitlines([keepends]) -> list of strings
                按行分隔,返回一个字符串元素的列表,keepends默认为False,不保留换行符,为True表示保留换行符
                >>> test = '''my name is ZJ
                ... I love Python
                ... I want coding my program
                ... '''
                >>> test
                'my name is ZJ
I love Python
I want coding my program
'
                >>> test.splitlines()
                ['my name is ZJ', 'I love Python', 'I want coding my program']
                >>> test.splitlines(True)
                ['my name is ZJ
', 'I love Python
', 'I want coding my program
']
                >>> 
            partition:
                partition(...)
                    S.partition(sep) -> (head, sep, tail)
                对字符串进行分隔,sep为分隔符,返回一个三个元素的元组。
                >>> line = 'url:http://www.baidu.com'
                >>> line.partition(':')
                ('url', ':', 'http://www.baidu.com')
            rpartition:                
                rpartition(...)
                    S.rpartition(sep) -> (head, sep, tail)
                对字符串进行分隔,从右往左进行分隔,sep为分隔符,返回一个三个元素的元组。
                >>> line.rpartition(':')
                ('url:http', ':', '//www.baidu.com')
                >>> 
        字符串修改(自然语言的修改):
            capitalize:
                capitalize(...)
                    S.capitalize() -> str
                对字符串行首进行处理,首字母大写
                >>> s.capitalize()
                'My name is zj'
                >>> 
                            

            title:
                title(...) method of builtins.str instance
                    S.title() -> str
                将字符串的每个单词的首字母变成大写。
                >>> s.title()
                'My Name Is Zj'
                >>> 
            lower:
                lower(...) method of builtins.str instance
                    S.lower() -> str
                将字符串中所有的大写字母变成小写。
                >>> s.lower()
                'my name is zj'
                >>> 
            upper:
                upper(...) method of builtins.str instance
                    S.upper() -> str
                将字符串的所有小写字母都变成大写。
                >>> s.upper()    
                'MY NAME IS ZJ'
                >>> 
            swapcase:
                swapcase(...) method of builtins.str instance
                    S.swapcase() -> str
                将字符串中的小写字母变成大写,大写字母变成小写。
                'my name is ZJ'
                >>> s1 = s.title()
                >>> s1
                'My Name Is Zj'
                >>> s1.swapcase()
                'mY nAME iS zJ'

            center:
                center(...) method of builtins.str instance
                    S.center(width[, fillchar]) -> str    
                将字符串进行居中输出,width,指定字符串宽度,fillchar为填充符,默认为空格,可选参数。
                >>> s.center(50)
                '                  my name is ZJ                   '
                >>> s.center(50,'#')
                '##################my name is ZJ###################'
                >>>
                
            ljust:                
                ljust(...) method of builtins.str instance
                    S.ljust(width[, fillchar]) -> str
                对字符串进行右填充,l为left,有效字符位于整个字符串的左边。
                >>> s.ljust(30)
                'my name is ZJ                 '
                >>> s.ljust(30, '#')
                'my name is ZJ#################'
                >>> 
            rjust:
                rjust(...) method of builtins.str instance
                    S.rjust(width[, fillchar]) -> str
                对字符串进行左填充,r为right,有效字符位于整个字符串的右边。
                >>> s.rjust(30)
                '                 my name is ZJ'
                >>> s.rjust(30, '#')
                '#################my name is ZJ'
                >>> 
            zfill:
                zfill(...) method of builtins.str instance
                    S.zfill(width) -> str
                使用0对字符串左侧进行填充,width为指定字符宽度。
                >>> s.zfill(30)
                '00000000000000000my name is ZJ'
                >>> 
                
            strip:
                strip(...) method of builtins.str instance
                    S.strip([chars]) -> str
                默认为删除字符串两侧的空白(' '、
、-t),指定参数chars时为删除两侧指定的的字符,不指定chars为默认删除空白。
                >>> a
                ' 
  zhang san li si      	   
 '
                >>> a.strip()
                'zhang san li si'
                >>> 
                >>> a.strip('!')
                'this is !!!a !!!test'
                >>>
                
            rstrip:
                rstrip(...)
                    S.rstrip([chars]) -> str
                默认为删除字符串右侧的空白(' '、
、-t),指定参数chars时为删除右侧指定的的字符,不指定chars为默认删除空白。
                >>> a = ' 
  zhang san li si      	   
 '
                >>> a.rstrip()
                ' 
  zhang san li si'
                >>> a = '!!!!!this is !!!a !!!test!!!!!!!' 
                >>> a.rstrip('!')
                '!!!!!this is !!!a !!!test'

            lstrip:
                lstrip(...)
                    S.lstrip([chars]) -> str
                默认为删除字符串左侧的空白(' '、
、-t),指定参数chars时为删除左侧指定的的字符,不指定chars为默认删除空白。
                >>> a = ' 
  zhang san li si      	   
 '
                >>> a.lstrip()
                'zhang san li si      	   
 '
                >>> a = '!!!!!this is !!!a !!!test!!!!!!!'
                >>> a.lstrip('!')
                'this is !!!a !!!test!!!!!!!'
        
        字符串判断:
            startswith:
                startswith(...)
                    S.startswith(prefix[, start[, end]]) -> bool
                判断字首是否为指定字符,prefix为指定的字首字符,默认从字符串第一位匹配,[,start[, end]]为可选参数,值为索引下标,表示指定匹配区域,返回一个boo类型。
                >>> a = '###test!!!!'
                >>> a.startswith('#')
                True
                >>> a.startswith('t', 3, 5)
                True
                >>> a.startswith('#', 3, 5) 
                False
                >>> a.startswith('#', -4, -1)
                False
                >>> a.startswith('!', -4) 
                True
                >>>
            endstwith:
                endswith(...)
                    S.endswith(suffix[, start[, end]]) -> bool
                判断字尾是否为指定字符,suffix为指定的字尾字符,默认从字符串最后一位匹配,[,start[, end]]为可选参数,值为索引下标,表示指定匹配区域,返回一个boo类型。
                >>> a
                '###test!!!!'
                >>> a.endswith('!')
                True
                >>> a.endswith('t', 4, 6) 
                False
                >>> a[4:6]
                'es'
                >>> a[4:7]
                'est'
                >>> a.endswith('t', 4, 7)
                True
                >>> a.endswith('!', 4)    
                True
                >>> 
        字符串查找/替换:
            count:
                count(...)
                    S.count(sub[, start[, end]]) -> int
                跟list的count用法一样,统计字符串中指定字符的个数,返回一个整数类型,sub为指定字符,[, start[, end]]为可选参数,值为索引下标,指定统计的区域。
                >>> a = 'aaabbbaaabbbcccaaa'
                >>> a.count('a')
                9
                >>> a.count('a', 4)
                6
                >>> a.count('a', 4, 10)
                3
                >>> 
            find:
                find(...)
                    S.find(sub[, start[, end]]) -> int
                查找指定字符在字符串中第一次出现的的位置(从左往右查找),返回一个整形(索引下标),sub为指定字符,[, start[,为可选参数,值为索引下标,指定查找区域,如果字符串中没有指定的字符,则返回-1 rfind:
                rfind(...)
                    S.rfind(sub[, start[, end]]) -> int                
                查找指定字符在字符串中第一次出现的的位置(从右往左查找),返回一个整形(索引下标),sub为指定字符,[, start[,为可选参数,值为索引下标,指定查找区域,如果字符串中没有指定的字符,则返回-1>>> a
                'aaabbbaaabbbcccaaa'
                >>> a.rfind('b')
                11
                >>> a.rfind('bbb')
                9
                >>> a.rfind('bbb', 0, 10)
                3
                >>> a.rfind('bbb', 0, 20)
                9
                >>> a.rfind('bbb', 0, 1) 
                -1
                >>> 
            index:
                index(...)
                    S.index(sub[, start[, end]]) -> int
                用法与find一样,唯一与find的区别是,在找不到指定字符时find方法会返回一个-1,而index则会抛出一个ValueError异常。
                >>> a
                'aaabbbaaabbbcccaaa'
                >>> a.index('b')
                3
                >>> a.index('bbb')
                3
                >>> a.index('bbb', 4, 10)
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                ValueError: substring not found
                >>> a.index('bbb', 4, 20)
                9
            rindex:
                rindex(...)
                    S.rindex(sub[, start[, end]]) -> int                
                用法与rfind一样,唯一与rfind的区别是,在找不到指定字符时rfind方法会返回一个-1,而rindex则会抛出一个ValueError异常。
                >>> a
                'aaabbbaaabbbcccaaa'
                >>> a.rindex('b') 
                11
                >>> a.rindex('bbb')
                9
                >>> a.rindex('bbb', 4, 10)
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                ValueError: substring not found
                >>> a.rindex('bbb', 4, 20)
                9
                >>> a.rindex('b', 4, 20)  
                11
                >>> 
            replace:
                replace(...)
                    S.replace(old, new[, count]) -> str        
                替换字符串中的指定字符,返回替换完成后的新字符串,不会对原字符串进行修改,old为指定替换的字符,new为替换后的字符,count为可选参数,默认全字符串匹配替换,指定count为从左到右替换的次数。
                >>> a
                'aaabbbaaabbbcccaaa'
                >>> a.replace('aaa', '123')
                '123bbb123bbbccc123'
                >>> a.replace('aaa', '123' , 1)
                '123bbbaaabbbcccaaa'
                >>> a.replace('aaa', '123' , 2) 
                '123bbb123bbbcccaaa'
                >>> 
原文地址:https://www.cnblogs.com/LouisZJ/p/5674540.html