1. 程式人生 > >python 字符串操作二 內建函數

python 字符串操作二 內建函數

cal dig 切片 __iter__ www exp () [1] partition

一、查看字符串的內建函數

>>> 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.title
a.casefold      a.expandtabs    a.isalnum       a.islower       a.isupper       a.maketrans     a.rjust         a.splitlines    a.translate
a.center        a.find          a.isalpha       a.isnumeric     a.join          a.partition     a.rpartition    a.startswith    a.upper
a.count         a.format        a.isdecimal     a.isprintable   a.ljust         a.replace       a.rsplit        a.strip         a.zfill
a.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‘)

>>> d
b‘\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 字符串操作二 內建函數