Python string模塊經常使用方法

前言

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

String模塊中

>>> 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

  • s.center() | center(s, width[, fillchar])
  • s.ljust() | ljust(s, width[, fillchar])
  • s.rjust() | rjust(s, width[, fillchar])
  • s.zfill() | zfill(s, width[, fillchar])
  • s表明字符串,width表明字符串的長度,fillchar表明填充的字符,都是返回填充後的字符串,s不變
>>>"abc".center(5,'-') #用-填充,字符串在中間
'-abc-'
>>>"abc".ljust(5,'-') #用-填充,字符串在左邊
'abc--'
>>>"abc".rjust(5,'-') #用-填充,字符串在右邊
'--abc'
>>>"abc".zfill(5)   #0值填充,字符串在右邊
'00abc'

大小寫轉換

  • str.lower() #把字母轉成小寫
  • str.upper() #把字母轉成大寫
  • str.swapcase() #大小寫互換
  • str.capitalize() #句子首字母大寫
  • str.title() #每一個單詞首字母大寫
>>> import string
>>> str = "Python"
>>> str.lower()
'python'
>>> str.upper()
'PYTHON'
>>> str.swapcase()
'pYTHON'
>>> str.title()
'Python Is Good'

字符串判斷(返回布爾值)

  • str.isalpha() #是否全是字母,並至少有一個字符
  • str.isdigit() #是否全是數字,並至少有一個字符
  • str.isspace() #是否全是空白字符,並至少有一個字符
  • str.islower() #字母是否全是小寫
  • str.isupper() #字母是否即是大寫
  • str.istitle() #是不是首字母大寫的,不容許其餘字母大寫!
  • str.startwith(prefix[,start[,end]])#是否以prefix開頭
  • str.endwith(suffix[,start[,end]]) #以suffix結尾
  • 簡單的查詢是否存在在目標串中能夠用in判斷
自行嘗試

string模塊的常量

  • string.digits #數字0~9
  • string.letters #全部字母(大小寫)
  • string.lowercase #全部小寫字母
  • string.uppercase #全部大寫字母
  • string.printable #可打印字符的字符串
  • string.punctuation #全部標點
>>> 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.find(substr, [start, [end]]) //返回str中出現substr的第一個字母的標號,若是str中沒有substr則返回-1。start和end做用就至關於在str[start:end]中搜索。
  • str.rfind(substr, [start, [end]]) //返回str中最後出現的substr的第一個字母的標號,若是str中沒有substr則返回-1,也就是說從右邊算起的第一次出現的。
  • str.index(substr, [start, [end]]) //與find()相同,只是在str中沒有substr時,會返回一個運行時錯誤
  • str.rindex(substr, [start, [end]]) //與rfind()相同,只是在str中沒有substr時,會返回一個運行時錯誤
  • str.count(substr, [start, [end]]) //計算substr在str中出現的次數
自行測試

字符串的分割和組合

  • str.split([sep, [maxsplit]]) //以sep爲分隔符,把str分紅一個list。maxsplit表示分割的次數。默認的分割符爲空白字符。
  • str.rsplit([sep, [maxsplit]])
  • str.splitlines([keepends]) //這倆個貌似效果同樣,都是把str按照行分割符分爲一個list,keepends是一個bool值,若是爲真每行後而會保留行分割符。
  • str.join(seq) //官方解釋:Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space.//就是將數組鏈接成字符串返回
>>> 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.replace(oldstr, newstr, [count]) //把string中的oldstar替換爲newstr,count爲替換次數。
  • string.strip([chars]) //把string中左右兩邊包含chars中有的字符所有去掉,默認去掉空格
  • string.lstrip([chars]) //把string中左邊包含chars中有的字符所有去掉
  • string.rstrip([chars]) //把str中右邊包含chars中有的字符所有去掉
  • string.expandtabs([tabsize]) //把string中的tab字符替換沒空格,每一個tab替換爲tabsize個空格,默認是2個?(我這裏是兩個)
>>> 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      '

字符串轉數字

  • string.atoi(str[,base]) #將字符串做爲base進制進行轉換,默認將字符串認爲是十進制,都會轉換成十進制
  • string.atof(str) #將str轉換成浮點型數字
>>> 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
>>>

小技巧

  1. 倒序字符串
>>> string = 'python'
>>> string[::-1]
'nohtyp'
  1. 固定長度分割字符串
>>> import re
>>> string
'python'
>>> re.findall(r'.{1,3}',string)
['pyt', 'hon']
  1. 字符串鏈接
使用'+'號鏈接n個字符串須要申請n-1次內存
使用join()須要申請1次內存
  1. 數字字符之間的轉換
>>> str(233)    #將整數轉換成字符串
'233'
>>> chr(97)     #將整數轉換成ASCII字符
'a'
>>> ord('a')    #將字符轉換成ASCII碼整數
97
相關文章
相關標籤/搜索