Python学习之字符串函数

下面是在看python核心编程中序列字符串中提到的一些函数,根据自己的学习理解总结了下,方便日后用到的时候查看。

   1、string.capitalize()

把字符串的第一个字符大写

      例子:    a = 'name is : '
                print a.capitalize()  ==》Name is :

   2、string.count(str, beg=0, end = len(string))

  返回str 在string 里面出现的次数,如果beg 或者end 指定则返回指定范围内str 出现的次数

      例子:   

  a = 'test plan is to show the plan of the project. '

        print a.count('plan')       #==> 2
        print a.count('plan',9,18)  #==> 0

   3、string.decode(encoding='UTF-8',errors='strict')

以encoding 指定的编码格式解码string,如果出错默认报一个ValueError 的异常, 除非errors 指定的是'ignore'  或者'replace'

   4、string.encode(encoding='UTF-8',errors='strict')

以encoding 指定的编码格式编码string,如果出错默认报一个ValueError 的异常,除非errors 指定的是'ignore' 或者'replace'

  
   5、检查字符串是否以某一字符开头或结尾
    string.endswith(obj, beg=0,end=len(string)): 检查字符串是否以obj 结束,如果beg 或者end 指定则检查指定的范围内是否以obj 结束,如果是,返回True,否则    返回False.

    string.startswith(obj, beg=0,end=len(string)): 检查字符串是否是以obj 开头,是则返回True,否则返回False。如果beg 和end 指定值,则在指定范围内检查.

    例:
    a = 'test plan is to show the plan of the project.'
    print a.endswith('et')          #==> False
    print a.endswith('t.')          #==> True
    print a.endswith('t',0,3)       #==> False
    print a.endswith('t',0,4)       #==> True

    print a.startswith('et')          #==> False
    print a.startswith('te')          #==> True
    print a.startswith('te',3,8)       #==> False
    print a.startswith('sh',5)       #==> Flase

   6、string.expandtabs(tabsize=8)

把字符串string 中的tab 符号转为空格,默认的空格数tabsize 是8.

    例:
    a = 'what is your favorite color    ?' #your 前面加了个tab符号
    print a                 #==> what is     your favorite color    ?
    print a.expandtabs()    #==> what is         your favorite color    ?
    print a.expandtabs(2)   #==> what is   your favorite color    ?

   7、字符串中查找某一字符或字符串是否存在: string.find() 与 string.rfind()

    string.find(str, beg=0,end=len(string)) 检测str 是否包含在string 中,如果beg 和end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1

    例:
        a = 'what is your favorite color    ?'
        print a.find('str')        #==> -1
        print a.find(' ')        #==> 8
        print a.find('your')        #==> 9        
        print a.find('your', 1,5)    #==> -1

    string.rfind(str, beg=0,end=len(string))类似于find()函数,不过是从右边开始查找.    

        print a.rfind('your')        #==> 9    
        print a.rfind('a')        #==> 15       从右边开始找到的是favorite中的a
        print a.find('a')        #==> 2       从左边开始找到的是what中的a
 

   8、 字符串中查找某一字符所在的位置: string.index()与string.rindex

    string.index(str, beg=0,end=len(string)) 跟find()方法一样,只不过如果str 不在string 中会报一个异常.
    string.rindex( str, beg=0,end=len(string)) 类似于index(),不过是从右边开始.

    例:
        a = 'what is your favorite color    ?'
        print a.index('a')        #==> 2       从左边开始找到的是what中的a
        print a.rindex('a')        #==> 15       从右边开始找到的是favorite中的a

   9、字符串数值判断

    string.isalnum(): 如果string 至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False

    string.isalpha(): 如果string 至少有一个字符,并且所有字符都是字母则返回True,否则返回False

    string.isdecimal(): 如果string 只包含十进制数字则返回True 否则返回False. 只适用于unicode字符

    string.isdigit(): 如果string 只包含数字则返回True 否则返回False.

    string.isnumeric()b, c, d 如果string 中只包含数字字符,则返回True,否则返回False。 只适用于unicode字符  
    例:
        a = 'what is your favorite color    ?' #your 前面加了个tab符号
        c = 'what'
        b ='123456'
        d = '123 456'

        print a.isalnum()        #==> False
        print a.isalpha()        #==> False
        print c.isalpha()        #==> True
        print a.isdigit()        #==> False
        print b.isalnum()        #==> True
        print b.isalpha()        #==> False
        print b.isdigit()        #==> True

        print d.isdigit()        #==> False
        print d.isalnum()        #==> False

   12、字符大小写转换、大小写判断:

    string.lower() 转换string 中所有大写字符为小写.
    string.upper() 转换string 中的小写字母为大写
    string.swapcase() 翻转string 中的大小写

    string.islower()b, c 如果string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False
    string.isupper()b, c 如果string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False
例:
        c = 'wh at'
        d = 'What'
        e = 'WHAT9'
        print c.isupper()        #==> False    
        print c.islower()        #==> True

        print d.isupper()        #==> False
        print d.islower()        #==> False        
        print e.isupper()        #==> True
        print e.islower()        #==> False

        print d.swapcase()        #==> wHAT
        print d.lower()            #==> what
        print d.upper()            #==> WHAT

   13、string.isspace()b, c 如果string 中只包含空格,则返回True,否则返回False.

   14、string.istitle() 与string.title   

string.istitle()b, c 如果string 是标题化的(见title())则返回True,否则返回False
string.title() 返回"标题化"的string,就是说所有单词都是以大写开始,其余字母均为小写(见istitle())

    例:
        e = 'WHAT9'
        
        print e.title()            #==>What9        
        titleStr = e.title()
        print e.istitle()        #==>False
        print titleStr .istitle()    #==>True

        f ='123 456'
        print f.title()            #==>123 456
        titlef = e.title()
        print f.istitle()        #==>False
        print titlef .istitle()        #==>False

   15、string.join(seq) Merges (concatenates)以string 作为分隔符,将seq 中所有的元素(的字符串表示)合并为一个新的字符串

  例:
        a = 'test'
        b = 'paul is a tester'
        print b.join(a)
        #==> tpaul is a testerepaul is a testerspaul is a testert

   16、去空格函数:strip()、lstrip()与rstrip()

    string.strip([obj]) 在string 上执行lstrip()和rstrip()
    string.rstrip() 删除string 字符串末尾的空格.
    string.lstrip() 截掉string 左边的空格

   17、字符串对齐函数 string.ljust()与string.rjust()

string.ljust(width)返回一个原字符串左对齐,并使用空格填充至长度width 的新字符串
string.rjust(width)返回一个原字符串右对齐,并使用空格填充至长度width 的新字符串

    例:
        a = 'test'
        c=a.ljust(20)
        d=a.rjust(20)

        print len(c)        #==>20
        print len(d)        #==>20
        print c == d        #==>False

        print c[19]        #==> 结果输出为空
        print d[19]        #==> t

   18、string.partition(str) 与 string.rpartition(str) 

string.partition(str) 有点像find()和split()的结合体,从str 出现的第一个位置起,把字符串string 分成一个3 元素的元组(string_pre_str,str,string_post_str), 如果string 中不包含str 则string_pre_str == string, str和string_post_str均为空

string.rpartition(str)e 类似于partition()函数,不过是从右边开始查找. 如果string 中不包含str 则string_post_str == string, str和string_pre_str均为空
    例:
        a = 'This is a example for string.partition or string.rpartition'

        print a.partition('or')    
            #==> ('This is a example f', 'or', ' string.partition or string.rpartition')

        print a.rpartition('or')
            #==> ('This is a example for string.partition ', 'or', ' string.rpartition')

        print a.partition('or1')
            #==>('This is a example for string.partition or string.rpartition', '', '')
        print a.rpartition('or1')
            #==>('', '', 'This is a example for string.partition or string.rpartition')


   19、string.replace(str1, str2,num=string.count(str1))

把string 中的str1 替换成str2,如果在string中找不到str1,则不替换。如果num 指定,则替换不超过num 次.   

例:
        a = 'This is a example for string.partition or string.rpartition'

        print a.replace('or','OR')
            #==>This is a example fOR string.partition OR string.rpartition

        print a.replace('or','OR',1)
            #==>This is a example fOR string.partition or string.rpartition

   20、string.split(str="", num=string.count(str)): 以str 为分隔符切片string,如果num有指定值,则仅分隔num 个子字符串

    例:
        print a.split('or')
        print a.split('or',1)
        print a.split('or1')

        ==>['This is a example f', ' string.partition ', ' string.rpartition']
           ['This is a example f', ' string.partition or string.rpartition']
              ['This is a example for string.partition or string.rpartition']

   21、string.splitlines(num=string.count(' ')): 按照行分隔,返回一个包含各行作为元素的列表,如果num 指定则仅切片num 个行.

   22、string.translate(str, del=""): 根据str 给出的表(包含256 个字符)转换string 的字符,要过滤掉的字符放到del 参数中

    例:
        from string import maketrans
        d = 'What'
        intab ='at'
        outtab = '14'
        trantab = maketrans(intab,outtab)

        print d.translate(trantab)        #==> Wh14

        print d.translate(trantab,'a')        #==> Wh4
    
   23、string.zfill(width) 返回长度为width 的字符串,原字符串string 右对齐,前面填充0
    例:
        d = 'What'
        print d.zfill(8)        #==>0000What        

原文地址:https://www.cnblogs.com/binghaixuefeng/p/5123213.html