標籤:ack char map back swa lower module iter tran
一、查看字串的內建函數
>>> dir(str)[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,
‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘,
‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘,
‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘,
‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘,
‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘,
‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
In [1]: a = ‘123‘In [2]: a.a.capitalize a.endswith a.index a.isidentifier a.istitle a.lstrip a.rindex a.split a.titlea.casefold a.expandtabs a.isalnum a.islower a.isupper a.maketrans a.rjust a.splitlines a.translatea.center a.find a.isalpha a.isnumeric a.join a.partition a.rpartition a.startswith a.uppera.count a.format a.isdecimal a.isprintable a.ljust a.replace a.rsplit a.strip a.zfilla.encode a.format_map a.isdigit a.isspace a.lower a.rfind a.rstrip a.swapcase
二、常用的字串內建函數
1、capitalize,字串的第一個字元大寫
>>> a = ‘today is a good day.‘>>> a.capitalize()‘Today is a good day.‘
2、 casefold,將所有字元小寫,Unicode所有字元均適用
>>> b‘TODAY IS A GOOD DAY.‘>>> b.casefold()‘today is a good day.‘
3、lower,將所有字元小寫,只適用ASCii
>>> b‘TODAY IS A GOOD DAY.‘>>> b.lower()‘today is a good day.‘
4、upper,將所有字元大寫
>>> a‘today is a good day.‘>>> a.upper()‘TODAY IS A GOOD DAY.‘
5、center,返回一個原字串置中,並使用空格填充至長度 width 的新字串,文法:str.center(width[, fillchar])
>>> a‘today is a good day.‘>>> a.center(40)‘ today is a good day. ‘
6、count,用於統計字串裡某個字元出現的次數。選擇性參數為在字串搜尋的開始與結束位置,文法:str.count(sub, start= 0,end=len(string))
>>> a‘today is a good day.‘>>> a.count(‘a‘)3>>> a.count(‘a‘, 5, -2)2
7、encode,以 encoding 指定的編碼格式編碼字串。errors參數可以指定不同的錯誤處理方案,文法:str.encode(encoding=‘UTF-8‘,errors=‘strict‘)
errors -- 設定不同錯誤的處理方案。預設為 ‘strict‘,意為編碼錯誤引起一個UnicodeError。 其他可能得值有 ‘ignore‘, ‘replace‘, ‘xmlcharrefreplace‘, ‘backslashreplace‘ 以及通過 codecs.register_error() 註冊的任何值。
>>> c = ‘你好‘>>> c.encode(encoding=‘utf-8‘)b‘\xe4\xbd\xa0\xe5\xa5\xbd‘
8、decode,以 encoding 指定的編碼格式解碼字串。預設編碼為字串編碼,文法:str.decode(encoding=‘UTF-8‘,errors=‘strict‘)
>>> db‘\xe4\xbd\xa0\xe5\xa5\xbd‘>>> d.decode(encoding=‘utf-8‘)‘你好‘
9、startwith,檢查字串是否是以指定子字串開頭,如果是則返回 True,否則返回 False。如果參數 beg 和 end 指定值,則在指定範圍內檢查,文法:str.startswith(str, beg=0,end=len(string))
>>> a‘today is a good day.‘>>> a.startswith(‘today‘)True>>> a.startswith(‘day‘)False>>> a.startswith(‘day‘, 5)False>>> a.startswith(‘today‘, 5)False
10、endwith,判斷字串是否以指定尾碼結尾,如果以指定尾碼結尾返回True,否則返回False。選擇性參數"start"與"end"為檢索字串的開始與結束位置,文法:str.endswith(suffix[, start[, end]])
>>> a‘today is a good day.‘>>> a.endswith(‘day.‘)True>>> a.endswith(‘today.‘)False>>> a.endswith(‘day.‘, 5)True
11、expandtabs,把字串中的 tab 符號(‘\t‘)轉為空白格,tab 符號(‘\t‘)預設的空格數是 8,文法:str.expandtabs(tabsize=8)
>>> e = ‘today is a good day.‘>>> e‘\ttoday is \ta good day.\t\t‘>>> e.expandtabs(4)‘ today is a good day. ‘
12、find,檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,如果包含子字串返回開始的索引值,否則返回-1,文法:str.find(str, beg=0, end=len(string))
>>> a‘today is a good day.‘>>> a.find(‘a‘)3>>> a.find(‘a‘, 10)17>>> a.find(‘abc‘)-1
13、index,檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,該方法與 python find()方法一樣,只不過如果str不存在 string中會報一個異常,文法:str.index(str, beg=0, end=len(string))
>>> a‘today is a good day.‘>>> a.index(‘a‘)3>>> a.index(‘a‘, 10)17>>> a.index(‘abc‘, 10)Traceback (most recent call last): File "<console>", line 1, in <module>ValueError: substring not found
14、isalnum,檢測字串是否由字母和數字組成
>>> a = ‘wang512‘>>> a.isalnum()True>>> a = ‘wang‘>>> a.isalnum()True>>> a = ‘512‘>>> a.isalnum()True>>> a = ‘wang 512‘>>> a.isalnum()False
15、isalnum,檢測字串是否只由字母組成
>>> a = ‘wang‘>>> a.isalpha()True>>> a = ‘512‘>>> a.isalpha()False
16、isdecimal ,檢查字串是否只包含十進位字元。這種方法只存在於unicode對象
>>> a = ‘12345‘>>> a.isdecimal()True>>> a = ‘wang‘>>> a.isdecimal()False
17、isdigit,檢測字串是否只由數字組成
>>> a = ‘12345‘>>> a.isdigit()True>>> a = ‘wang‘>>> a.isdigit()False
18、isidentifier,檢測字串是否以字母開頭
>>> a.isidentifier()False>>> a = ‘wang‘>>> a.isidentifier()True
19、islower,檢測字串是否由小寫字母組成。
>>> a = "wang">>> a.islower()True>>> a = "Wang">>> a.islower()False
20、isupper,檢測字串中所有的字母是否都為大寫。
>>> a = "WANG">>> a.isupper()True>>> a = "Wang">>> a.isupper()False
21、isnumeric,檢測字串是否只由數字組成。這種方法是只針對unicode對象。
>>> a = ‘12345‘>>> a.isnumeric()True>>> a = ‘w123‘>>> a.isnumeric()False
22、isprintable,包含所有可列印字元的字串。
23、isspace,檢測字串是否只由空格組成。
24、istitile,檢測字串中所有的單詞拼字首字母是否為大寫,且其他字母為小寫。
25、join,將序列中的元素以指定的字元串連產生一個新的字串,文法:str.join(sequence)
>>> a = [‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> ‘,‘.join(a)‘a,b,c,d‘
26、ljust,返回一個原字串靠左對齊,並使用空格填充至指定長度的新字串。如果指定的長度小於原字串的長度則返回原字串,文法:str.ljust(width[, fillchar])
>>> a = ‘wang‘>>> a.ljust(10, ‘>‘)‘wang>>>>>>‘
27、rjust,返回一個原字串靠右對齊,並使用空格填充至長度 width 的新字串。如果指定的長度小於字串的長度則返回原字串,文法:str.rjust(width[, fillchar])
>>> a = ‘wang‘>>> a.rjust(10, ‘<‘)‘<<<<<<wang‘
28、split,通過指定分隔字元對字串進行切片,如果參數num 有指定值,則僅分隔 num 個子字串,文法:str.split(str="", num=string.count(str)).
>>> a = ‘wang wang wang wang‘>>> a.split(‘a‘, 3)[‘w‘, ‘ng w‘, ‘ng w‘, ‘ng wang‘]
29、rsplit
>>> a‘wang wang wang wang‘>>> a.rsplit(‘a‘, 3)[‘wang w‘, ‘ng w‘, ‘ng w‘, ‘ng‘]
30、splitlines,按照行(‘\r‘, ‘\r\n‘, \n‘)分隔,返回一個包含各行作為元素的列表,如果參數 keepends 為 False,不包含分行符號,如果為 True,則保留分行符號,文法:str.splitlines([keepends])
>>> a = ‘ab c\n\nde fg\rkl\r\n‘>>> a.splitlines()[‘ab c‘, ‘‘, ‘de fg‘, ‘kl‘]>>> a.splitlines(False)[‘ab c‘, ‘‘, ‘de fg‘, ‘kl‘]>>> a.splitlines(True)[‘ab c\n‘, ‘\n‘, ‘de fg\r‘, ‘kl\r\n‘]
31、strip,用於移除字串頭尾指定的字元(預設為空白格),文法:str.strip([chars])
32、rstrip,刪除 string 字串末尾的指定字元(預設為空白格),文法:str.rstrip([chars])
33、lstrip,用於截掉字串左邊的空格或指定字元,文法:str.lstrip([chars])
34、maketrans,用於建立字元對應表的轉換表,對於接受兩個參數的最簡單的調用方式,第一個參數是字串,表示需要轉換的字元,第二個參數也是字串表示轉換的目標,文法:str.maketrans(intab, outtab)
註:兩個字串的長度必須相同,為一一對應的關係。
35、translate,根據參數table給出的表(包含 256 個字元)轉換字串的字元, 要過濾掉的字元放到 del 參數中,文法:str.translate(table[, deletechars]);
>>> intab = "aeiou">>> outtab = "12345">>> trantab = ‘‘.maketrans(intab, outtab)>>> s = ‘abcdef‘>>> s.translate(trantab)‘1bcd2f‘>>> trantab{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
36、partition,用來根據指定的分隔字元將字串進行分割。如果字串包含指定的分隔字元,則返回一個3元的元組,第一個為分隔字元左邊的子串,第二個為分隔字元本身,第三個為分隔字元右邊的子串。文法:str.partition(str)
37、rpartition
>>> a = "http://www.baidu.com ://sina">>> a.partition(‘://‘)(‘http‘, ‘://‘, ‘www.baidu.com ://sina‘)>>> a.rpartition(‘://‘)(‘http://www.baidu.com ‘, ‘://‘, ‘sina‘)
38、
python 字串操作二 內建函數