Python的字符串方法

发布时间:2019-06-22 23:46:16编辑:auto阅读(1685)

    Python字符串方法:


    s.isdigit() -> bool  Return True if all characters in S are digits

    s.islower() -> bool   Return True if all cased characters in S are lowercase                   

    s.isspace() -> bool  Return True if all characters in S are whitespace

    s.istitle() -> bool  如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False.                   

    s.isupper() -> bool   如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False                  

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

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


    s.strip([chars]) -> string or unicode  截掉 string 左边和右边的空格或指定的字符,默认为空格

    s.rstrip([chars])-> string or unicode  删除 string 字符串末尾的指定字符(默认为空格).

    s.lstrip([chars])  -> string or unicode     用于截掉字符串左边的空格或指定字符               

    str = "     this is string example....wow!!!     ";
    print str.lstrip();
    print str.rstrip();
    print str.strip();
    str = "88888888this is string example....wow!!!8888888";
    print str.lstrip('8');
    print str.rstrip('8');
    print str.strip('8');



    s.split([sep [,maxsplit]]) -> list of strings  以 sep 为分隔符切片 string,如果 maxsplit有指定值,则仅分隔 maxsplit个子字符串

    s.rsplit([sep [,maxsplit]]) -> list of strings

    s='hello wolrd I love you'
    print s.split(' ',2)
    print s.rsplit(' ',2)
    str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
    print str.split( );
    print str.split(' ', 1 );
    print str.rsplit( );
    print str.rsplit(' ', 1 );


    s.splitlines(keepends=False)  -> list of strings        按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

    str1 = 'ab c\n\nde fg\rkl\r\n'
    print str1.splitlines();
    str2 = 'ab c\n\nde fg\rkl\r\n'
    print str2.splitlines(True)



    s.index(sub [,start [,end]]) -> int     跟find()方法一样,只不过如果sub不在 string中会报一个异常.

    s.rindex(sub [,start [,end]])  -> int  从右边开始.

    str1 = "this is string example....wow!!!";
    str2 = "exam";
     
    print str1.index(str2);
    print str1.index(str2, 10);
    print str1.index(str2, 40); #抛错
    
    str1 = "this is string example....wow!!!";
    str2 = "is";
    
    print str1.rindex(str2);
    print str1.index(str2);


    s.find(sub [,start [,end]])  -> int        检测 sub 是否包含在 string 中,如果 start 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1               

    s.rfind(sub [,start [,end]])  -> int   右边开始查找.返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。

    str = "this is really a string example....wow!!!";
    substr = "is";
    print str.rfind(substr); #5
    print str.rfind(substr, 0, 10); #5
    print str.rfind(substr, 10, 0); #-1
    print str.find(substr); #2
    print str.find(substr, 0, 10); #2
    print str.find(substr, 10, 0); #-1


    s.ljust(width[, fillchar]) -> string      返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

    s.rjust(width[, fillchar]) -> string

    str = "this is string example....wow!!!";
    print str.ljust(50, '0');
    print str.rjust(50, '0'); #000000000000000000this is string example....wow!!!


    s.partition(sep) -> (head, sep, tail)      find()和 split()的结合体,从str出现的第一个位置起,把字符string 分成一个3元素的元组 string_pre_str,str,string_post_str),如果 string 中不包含str 则 string_pre_str== string.

    s.rpartition(sep) -> (head, sep, tail)      类似于 partition()函数,不过是从右边开始查找.           


    str = "http://www.w3cschool.cc/"
    print str.partition("://") #('http', '://', 'www.w3cschool.cc/')
    print str.rpartition("://") #('http', '://', 'www.w3cschool.cc/')
    print str.split("://") #['http', 'www.w3cschool.cc/']


    s.capitalize() -> string        把字符串的第一个字符大写,其他字母变小写

    s = 'a, B'
    print s.capitalize() #A, b


    s.center(width[, fillchar]) -> string       返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

    str = 'runoob'
    print str.center(20, '*')
    print str.center(20)

       

    s.startswith(prefix[, start[, end]]) -> bool  用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查

    str = "this is string example....wow!!!";
    print str.startswith( 'this' );
    print str.startswith( 'is', 2, 4 );
    print str.startswith( 'this', 2, 4 );#False


    s.endswith(suffix[, start[, end]]) -> bool              用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。     

    str = "this is string example....wow!!!";
    suffix = "wow!!!";
    print str.endswith(suffix);
    print str.endswith(suffix,20);
    suffix = "is";
    print str.endswith(suffix, 2, 4);
    print str.endswith(suffix, 2, 6); #False


    s.count(sub[, start[, end]]) -> int    返回 sub 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 sub出现的次数                   

    str = "this is string example....wow!!!";
    sub = "i";
    print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
    sub = "wow";
    print "str.count(sub) : ", str.count(sub)


    s.join(iterable) -> string          join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串              

    str = "-";
    seq = ["a", "b", "c"]; # 字符串序列
    print str.join(seq);


    s.decode([encoding[,errors]]) -> object    以encoding指定的编码格式解码string,如果出错默认报一个ValueError的异常,除非 errors指定的是'ignore'或者'replace'   

    str = "this is string example....wow!!!";
    str = str.encode('base64','strict');
    print "Encoded String: " + str;
    print "Decoded String: " + str.decode('base64','strict')


    s.encode([encoding[,errors]]) -> object      以 encoding 指定的编码格式编码 string,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'                                       

    str = "this is string example....wow!!!";
    print "Encoded String: " + str.encode('base64','strict')
    print "Encoded String: " + str.encode('UTF-8','strict')


    s.swapcase() -> string        翻转 string 中的大小写

    s.lower()  -> string              转换 string 中的小写字母为小写           

    s.upper()    -> string          转换 string 中的小写字母为大写           

    s.title()-> string                 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写  

    str = "this is string example....wow!!!";
    print str.title();


    s.translate(table [,deletechars]) -> string              据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 deletechars参数中。

    python2的写法:
    
    import string   # 导入string模块
      
    intab = "aeiou"
    outtab = "12345"
    deltab = "thw"
      
    trantab = string.maketrans(intab,outtab) # 创建字符映射转换表
      
    test = "this is string example....wow!!!";
      
    print test.translate(trantab);
    print test.translate(trantab,deltab); # Python2中,删除指定字符在 translate() 方法中
    
    
    python3的写法:
    intab = "aeiou"
    outtab = "12345"
    deltab = "thw"
      
    trantab1 = str.maketrans(intab,outtab) # 创建字符映射转换表
    trantab2 = str.maketrans(intab,outtab,deltab) #创建字符映射转换表,并删除指定字符
      
    test = "this is string example....wow!!!"
      
    print(test.translate(trantab1))
    print(test.translate(trantab2))


    s.expandtabs([tabsize]) -> string    把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。     

    str = "this is\tstring example....wow!!!";
    print "Original string: " + str;
    print "Defualt exapanded tab: " +  str.expandtabs(); #默认一个空格替换\t
    print "Double exapanded tab: " +  str.expandtabs(16);


    s.replace(old, new[, count]) -> string  :返回的替换后的字符串,原来的字符串并不改变

    s='hello python,hello world,hello c++,hello java!'
    print s.replace('hello','Hello')#将字符串s中的所有'hello'子串,替换成'Hello',返回替换后的字符串,原字符串s不变
    print s.replace('hello','Hello',2)#将字符串s中的前2个'hello'子串,替换成'Hello'
    print s.replace('wahaha','haha')#要替换的'wahaha'子串不存在,直接返回原字符串


    s.format(*args, **kwargs) -> string     

    #通过位置格式化
    who=('北京','我')
    print '{1}去{0}'.format(*who)
    #通过关键字格式化
    who1={'where':'北京','who':'you'}
    print '{who}去{where}'.format(**who1)
    print '{:^20}'.format('你好啊') #居中对齐,后面带宽度
    print '{:>20}'.format('你好啊') #右对齐,后面带宽度
    print '{:<20}'.format('你好啊') #左对齐,后面带宽度
    print '{:*<20}'.format('你好啊') #左对齐,后面带宽度,不够就填空
    print '{:&>20}'.format('你好啊') #左对齐,后面带宽度,不够就填空
    print '{:.1f}'.format(4.234324525254) #精度和类型f
    print '{:.4f}'.format(4.1) #精度和类型f
    print '{:b}'.format(250) #二进制转换
    print '{:o}'.format(250) #八进制转换
    print '{:d}'.format(250) #十进制转换
    print '{:x}'.format(250) #十六进制转换
    print '{:,}'.format(100000000) #千位分隔符,这种情况只针对于数字
    print '{:,}'.format(235445.234235) #千位分隔符,这种情况只针对于数字


    s.zfill(width) -> string   返回长度为 width 的字符串,原字符串 string 右对齐,如果长度不够前面填充0

    s='hello wolrd I love you'
    print s.zfill(50)


关键字