我的覺的字符串處理是每一門編程語言的很是重要的基本功。 熟練處理運用這些方法處理字符串能節省大量時間。(誰讓我菜呢) 下面是記錄的一些經常使用的方法,之後遇到可能會慢慢補充。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