我的觉的字符串处理是每一门编程语言的很是重要的基本功。 熟练处理运用这些方法处理字符串能节省大量时间。(谁让我菜呢) 下面是记录的一些经常使用的方法,之后遇到可能会慢慢补充。java
>>> import string >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] help(string.你想要了解的方法)
四个方法:python
>>>"abc".center(5,'-') #用-填充,字符串在中间 '-abc-' >>>"abc".ljust(5,'-') #用-填充,字符串在左边 'abc--' >>>"abc".rjust(5,'-') #用-填充,字符串在右边 '--abc' >>>"abc".zfill(5) #0值填充,字符串在右边 '00abc'
>>> import string >>> str = "Python" >>> str.lower() 'python' >>> str.upper() 'PYTHON' >>> str.swapcase() 'pYTHON' >>> str.title() 'Python Is Good'
自行尝试
>>> import string >>> string.digits '0123456789' >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> 看起来很是有用哦,之前都是一个一个打。。。
自行测试
>>> str = "PQ is a fool" >>> str.split() ['PQ', 'is', 'a', 'fool'] >>> str2 = str.split() >>> '-'.join(str2) #用'-'链接字符串 'PQ-is-a-fool' >>> '-'.join(str2,2) >>> str3 = "PQ\ris\na\nfool" >>> str3 'PQ\ris\na\nfool' >>> str3.rsplit() ['PQ', 'is', 'a', 'fool'] >>> str3.splitlines() #看来默认是False ['PQ', 'is', 'a', 'fool'] >>> str3.splitlines(True) ['PQ\r', 'is\n', 'a\n', 'fool'] >>>
>>> string = " python " >>> string.replace('python','java') #将'python'替换成'java' ' java ' >>> string.strip() #去掉了两边的空格(空字符应该均可以,默认的) 'python' >>> string.rstrip() #去掉右边的空字符 ' python' >>> string.lstrip() #去掉左边的空字符 'python ' >>> string = "python\t" >>> string 'python\t' >>> string.expandtabs() #将tab换成了两个空格 'python ' >>> string.expandtabs(6) #将tab换成了六个空格 'python '
>>> import string >>> s = '233' >>> string.atoi(s) #将字符串转换成十进制数字 233 >>> string.atoi(s,16) #将字符串看成16进制转换成十进制数字 563 >>> string.atof(s) #将字符串转换成浮点数 233.0 >>> s = '0xff' >>> string.atoi(s,16) #将16进制字符串转换成十进制数字 255 >>> s = '123' #将字符串转换成长整型 >>> atol(s) 123L >>>
>>> string = 'python' >>> string[::-1] 'nohtyp'
>>> import re >>> string 'python' >>> re.findall(r'.{1,3}',string) ['pyt', 'hon']
使用'+'号链接n个字符串须要申请n-1次内存 使用join()须要申请1次内存
>>> str(233) #将整数转换成字符串 '233' >>> chr(97) #将整数转换成ASCII字符 'a' >>> ord('a') #将字符转换成ASCII码整数 97