Python 的內(nèi)置字符串方法小結(jié)
字符串處理是非常常用的技能,但 Python 內(nèi)置字符串方法太多,常常遺忘,為了便于快速參考,特地依據(jù) Python 3.5.1 給每個(gè)內(nèi)置方法寫(xiě)了示例并進(jìn)行了歸類(lèi),便于大家索引。
PS: 可以點(diǎn)擊概覽內(nèi)的綠色標(biāo)題進(jìn)入相應(yīng)分類(lèi)或者通過(guò)右側(cè)邊欄文章目錄快速索引相應(yīng)方法。
大小寫(xiě)轉(zhuǎn)換
str.capitalize()
將首字母轉(zhuǎn)換成大寫(xiě),需要注意的是如果首字沒(méi)有大寫(xiě)形式,則返回原字符串。
'adi dog'.capitalize()
# 'Adi dog'
'abcd 徐'.capitalize()
# 'Abcd 徐'
'徐 abcd'.capitalize()
# '徐 abcd'
'ß'.capitalize()
# 'SS'
str.lower()
將字符串轉(zhuǎn)換成小寫(xiě),其僅對(duì) ASCII 編碼的字母有效。
'DOBI'.lower()
# 'dobi'
'ß'.lower() # 'ß' 為德語(yǔ)小寫(xiě)字母,其有另一種小寫(xiě) 'ss', lower 方法無(wú)法轉(zhuǎn)換
# 'ß'
'徐 ABCD'.lower()
# '徐 abcd'
str.casefold()
將字符串轉(zhuǎn)換成小寫(xiě),Unicode 編碼中凡是有對(duì)應(yīng)的小寫(xiě)形式的,都會(huì)轉(zhuǎn)換。
'DOBI'.casefold()
# 'dobi'
'ß'.casefold() #德語(yǔ)中小寫(xiě)字母 ß 等同于小寫(xiě)字母 ss, 其大寫(xiě)為 SS
# 'ss'
str.swapcase()
對(duì)字符串字母的大小寫(xiě)進(jìn)行反轉(zhuǎn)。
'徐Dobi a123 ß'.swapcase()
#: '徐dOBI A123 SS' 這里的 ß 被轉(zhuǎn)成 SS 是一種大寫(xiě)
但需要注意的是 s.swapcase().swapcase() == s 不一定為真:
u'\xb5'
# 'µ'
u'\xb5'.swapcase()
# 'Μ'
u'\xb5'.swapcase().swapcase()
# 'μ'
hex(ord(u'\xb5'.swapcase().swapcase()))
Out[154]: '0x3bc'
這里 'Μ'(是 mu 不是 M) 的小寫(xiě)正好與 'μ' 的寫(xiě)法一致。
str.title()
將字符串中每個(gè)“單詞”首字母大寫(xiě)。其判斷“單詞”的依據(jù)則是基于空格和標(biāo)點(diǎn),所以應(yīng)對(duì)英文撇好所有格或一些英文大寫(xiě)的簡(jiǎn)寫(xiě)時(shí),會(huì)出錯(cuò)。
'Hello world'.title()
# 'Hello World'
'中文abc def 12gh'.title()
# '中文Abc Def 12Gh'
# 但這個(gè)方法并不完美:
"they're bill's friends from the UK".title()
# "They'Re Bill'S Friends From The Uk"
str.upper()
將字符串所有字母變?yōu)榇髮?xiě),會(huì)自動(dòng)忽略不可轉(zhuǎn)成大寫(xiě)的字符。
'中文abc def 12gh'.upper()
# '中文ABC DEF 12GH'
需要注意的是 s.upper().isupper() 不一定為 True。
字符串格式輸出
str.center(width[, fillchar])
將字符串按照給定的寬度居中顯示,可以給定特定的字符填充多余的長(zhǎng)度,如果指定的長(zhǎng)度小于字符串長(zhǎng)度,則返回原字符串。
'12345'.center(10, '*')
# '**12345***'
'12345'.center(10)
# ' 12345 '
str.ljust(width[, fillchar]); str.rjust(width[, fillchar])
返回指定長(zhǎng)度的字符串,字符串內(nèi)容居左(右)如果長(zhǎng)度小于字符串長(zhǎng)度,則返回原始字符串,默認(rèn)填充為 ASCII 空格,可指定填充的字符串。
'dobi'.ljust(10)
# 'dobi '
'dobi'.ljust(10, '~')
# 'dobi~~~~~~'
'dobi'.ljust(3, '~')
# 'dobi'
'dobi'.ljust(3)
# 'dobi'
str.zfill(width)
用 '0' 填充字符串,并返回指定寬度的字符串。
"42".zfill(5)
# '00042'
"-42".zfill(5)
# '-0042'
'dd'.zfill(5)
# '000dd'
'--'.zfill(5)
# '-000-'
' '.zfill(5)
# '0000 '
''.zfill(5)
# '00000'
'dddddddd'.zfill(5)
# 'dddddddd'
str.expandtabs(tabsize=8)
用指定的空格替代橫向制表符,使得相鄰字符串之間的間距保持在指定的空格數(shù)以?xún)?nèi)。
tab = '1\t23\t456\t7890\t1112131415\t161718192021'
tab.expandtabs()
# '1 23 456 7890 1112131415 161718192021'
# '123456781234567812345678123456781234567812345678' 注意空格的計(jì)數(shù)與上面輸出位置的關(guān)系
tab.expandtabs(4)
# '1 23 456 7890 1112131415 161718192021'
# '12341234123412341234123412341234'
str.format(^args, ^^kwargs)
格式化字符串的語(yǔ)法比較繁多,官方文檔已經(jīng)有比較詳細(xì)的 examples,這里就不寫(xiě)例子了,想了解的童鞋可以直接戳這里 Format examples.
str.format_map(mapping)
類(lèi)似 str.format(*args, **kwargs) ,不同的是 mapping 是一個(gè)字典對(duì)象。
People = {'name':'john', 'age':56}
'My name is {name},i am {age} old'.format_map(People)
# 'My name is john,i am 56 old'
字符串搜索定位與替換
str.count(sub[, start[, end]])
text = 'outer protective covering'
text.count('e')
# 4
text.count('e', 5, 11)
# 1
text.count('e', 5, 10)
# 0
str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]])
text = 'outer protective covering'
text.find('er')
# 3
text.find('to')
# -1
text.find('er', 3)
Out[121]: 3
text.find('er', 4)
Out[122]: 20
text.find('er', 4, 21)
Out[123]: -1
text.find('er', 4, 22)
Out[124]: 20
text.rfind('er')
Out[125]: 20
text.rfind('er', 20)
Out[126]: 20
text.rfind('er', 20, 21)
Out[129]: -1
str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]])
與 find() rfind() 類(lèi)似,不同的是如果找不到,就會(huì)引發(fā) ValueError。
str.replace(old, new[, count])
'dog wow wow jiao'.replace('wow', 'wang')
# 'dog wang wang jiao'
'dog wow wow jiao'.replace('wow', 'wang', 1)
# 'dog wang wow jiao'
'dog wow wow jiao'.replace('wow', 'wang', 0)
# 'dog wow wow jiao'
'dog wow wow jiao'.replace('wow', 'wang', 2)
# 'dog wang wang jiao'
'dog wow wow jiao'.replace('wow', 'wang', 3)
# 'dog wang wang jiao'
str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])
' dobi'.lstrip()
# 'dobi'
'db.kun.ac.cn'.lstrip('dbk')
# '.kun.ac.cn'
' dobi '.rstrip()
# ' dobi'
'db.kun.ac.cn'.rstrip('acn')
# 'db.kun.ac.'
' dobi '.strip()
# 'dobi'
'db.kun.ac.cn'.strip('db.c')
# 'kun.ac.cn'
'db.kun.ac.cn'.strip('cbd.un')
# 'kun.a'
static str.maketrans(x[, y[, z]]); str.translate(table)
maktrans 是一個(gè)靜態(tài)方法,用于生成一個(gè)對(duì)照表,以供 translate 使用。
如果 maktrans 僅一個(gè)參數(shù),則該參數(shù)必須是一個(gè)字典,字典的 key 要么是一個(gè) Unicode 編碼(一個(gè)整數(shù)),要么是一個(gè)長(zhǎng)度為 1 的字符串,字典的 value 則可以是任意字符串、None或者 Unicode 編碼。
a = 'dobi'
ord('o')
# 111
ord('a')
# 97
hex(ord('狗'))
# '0x72d7'
b = {'d':'dobi', 111:' is ', 'b':97, 'i':'\u72d7\u72d7'}
table = str.maketrans(b)
a.translate(table)
# 'dobi is a狗狗'
如果 maktrans 有兩個(gè)參數(shù),則兩個(gè)參數(shù)形成映射,且兩個(gè)字符串必須是長(zhǎng)度相等;如果有第三個(gè)參數(shù),則第三個(gè)參數(shù)也必須是字符串,該字符串將自動(dòng)映射到 None:
a = 'dobi is a dog'
table = str.maketrans('dobi', 'alph')
a.translate(table)
# 'alph hs a alg'
table = str.maketrans('dobi', 'alph', 'o')
a.translate(table)
# 'aph hs a ag'
字符串的聯(lián)合與分割
str.join(iterable)
用指定的字符串,連接元素為字符串的可迭代對(duì)象。
'-'.join(['2012', '3', '12'])
# '2012-3-12'
'-'.join([2012, 3, 12])
# TypeError: sequence item 0: expected str instance, int found
'-'.join(['2012', '3', b'12']) #bytes 為非字符串
# TypeError: sequence item 2: expected str instance, bytes found
'-'.join(['2012'])
# '2012'
'-'.join([])
# ''
'-'.join([None])
# TypeError: sequence item 0: expected str instance, NoneType found
'-'.join([''])
# ''
','.join({'dobi':'dog', 'polly':'bird'})
# 'dobi,polly'
','.join({'dobi':'dog', 'polly':'bird'}.values())
# 'dog,bird'
str.partition(sep); str.rpartition(sep)
'dog wow wow jiao'.partition('wow')
# ('dog ', 'wow', ' wow jiao')
'dog wow wow jiao'.partition('dog')
# ('', 'dog', ' wow wow jiao')
'dog wow wow jiao'.partition('jiao')
# ('dog wow wow ', 'jiao', '')
'dog wow wow jiao'.partition('ww')
# ('dog wow wow jiao', '', '')
'dog wow wow jiao'.rpartition('wow')
Out[131]: ('dog wow ', 'wow', ' jiao')
'dog wow wow jiao'.rpartition('dog')
Out[132]: ('', 'dog', ' wow wow jiao')
'dog wow wow jiao'.rpartition('jiao')
Out[133]: ('dog wow wow ', 'jiao', '')
'dog wow wow jiao'.rpartition('ww')
Out[135]: ('', '', 'dog wow wow jiao')
str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)
'1,2,3'.split(','), '1, 2, 3'.rsplit()
# (['1', '2', '3'], ['1,', '2,', '3'])
'1,2,3'.split(',', maxsplit=1), '1,2,3'.rsplit(',', maxsplit=1)
# (['1', '2,3'], ['1,2', '3'])
'1 2 3'.split(), '1 2 3'.rsplit()
# (['1', '2', '3'], ['1', '2', '3'])
'1 2 3'.split(maxsplit=1), '1 2 3'.rsplit(maxsplit=1)
# (['1', '2 3'], ['1 2', '3'])
' 1 2 3 '.split()
# ['1', '2', '3']
'1,2,,3,'.split(','), '1,2,,3,'.rsplit(',')
# (['1', '2', '', '3', ''], ['1', '2', '', '3', ''])
''.split()
# []
''.split('a')
# ['']
'bcd'.split('a')
# ['bcd']
'bcd'.split(None)
# ['bcd']
str.splitlines([keepends])
字符串以行界符為分隔符拆分為列表;當(dāng) keepends 為T(mén)rue,拆分后保留行界符,能被識(shí)別的行界符見(jiàn)官方文檔。
'ab c\n\nde fg\rkl\r\n'.splitlines()
# ['ab c', '', 'de fg', 'kl']
'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
# ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
"".splitlines(), ''.split('\n') #注意兩者的區(qū)別
# ([], [''])
"One line\n".splitlines()
# (['One line'], ['Two lines', ''])
字符串條件判斷
str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])
text = 'outer protective covering'
text.endswith('ing')
# True
text.endswith(('gin', 'ing'))
# True
text.endswith('ter', 2, 5)
# True
text.endswith('ter', 2, 4)
# False
str.isalnum()
字符串和數(shù)字的任意組合,即為真,簡(jiǎn)而言之:
只要 c.isalpha(), c.isdecimal(), c.isdigit(), c.isnumeric() 中任意一個(gè)為真,則 c.isalnum() 為真。
'dobi'.isalnum()
# True
'dobi123'.isalnum()
# True
'123'.isalnum()
# True
'徐'.isalnum()
# True
'dobi_123'.isalnum()
# False
'dobi 123'.isalnum()
# False
'%'.isalnum()
# False
str.isalpha()
Unicode 字符數(shù)據(jù)庫(kù)中作為 “Letter”(這些字符一般具有 “Lm”, “Lt”, “Lu”, “Ll”, or “Lo” 等標(biāo)識(shí),不同于 Alphabetic) 的,均為真。
'dobi'.isalpha()
# True
'do bi'.isalpha()
# False
'dobi123'.isalpha()
# False
'徐'.isalpha()
# True
str.isdecimal(); str.isdigit(); str.isnumeric()
三個(gè)方法的區(qū)別在于對(duì) Unicode 通用標(biāo)識(shí)的真值判斷范圍不同:
isdecimal: Nd,
isdigit: No, Nd,
isnumeric: No, Nd, Nl
digit 與 decimal 的區(qū)別在于有些數(shù)值字符串,是 digit 卻非 decimal ,具體戳 這里
num = '\u2155'
print(num)
# ⅕
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)
num = '\u00B2'
print(num)
# ²
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, True, True)
num = "1" #unicode
num.isdecimal(), num.isdigit(), num.isnumeric()
# (Ture, True, True)
num = "'Ⅶ'"
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)
num = "十"
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)
num = b"1" # byte
num.isdigit() # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
str.isidentifier()
判斷字符串是否可為合法的標(biāo)識(shí)符。
'def'.isidentifier()
# True
'with'.isidentifier()
# True
'false'.isidentifier()
# True
'dobi_123'.isidentifier()
# True
'dobi 123'.isidentifier()
# False
'123'.isidentifier()
# False
str.islower()
'徐'.islower()
# False
'ß'.islower() #德語(yǔ)大寫(xiě)字母
# False
'a徐'.islower()
# True
'ss'.islower()
# True
'23'.islower()
# False
'Ab'.islower()
# False
str.isprintable()
判斷字符串的所有字符都是可打印字符或字符串為空。Unicode 字符集中 “Other” “Separator” 類(lèi)別的字符為不可打印的字符(但不包括 ASCII 的空格(0x20))。
'dobi123'.isprintable()
# True
'dobi123\n'.isprintable()
Out[24]: False
'dobi 123'.isprintable()
# True
'dobi.123'.isprintable()
# True
''.isprintable()
# True
str.isspace()
判斷字符串中是否至少有一個(gè)字符,并且所有字符都是空白字符。
In [29]: '\r\n\t'.isspace()
Out[29]: True
In [30]: ''.isspace()
Out[30]: False
In [31]: ' '.isspace()
Out[31]: True
str.istitle()
判斷字符串中的字符是否是首字母大寫(xiě),其會(huì)忽視非字母字符。
'How Python Works'.istitle()
# True
'How Python WORKS'.istitle()
# False
'how python works'.istitle()
# False
'How Python Works'.istitle()
# True
' '.istitle()
# False
''.istitle()
# False
'A'.istitle()
# True
'a'.istitle()
# False
'甩甩Abc Def 123'.istitle()
# True
str.isupper()
'徐'.isupper()
# False
'DOBI'.isupper()
Out[41]: True
'Dobi'.isupper()
# False
'DOBI123'.isupper()
# True
'DOBI 123'.isupper()
# True
'DOBI\t 123'.isupper()
# True
'DOBI_123'.isupper()
# True
'_123'.isupper()
# False
字符串編碼
str.encode(encoding="utf-8", errors="strict")
fname = '徐'
fname.encode('ascii')
# UnicodeEncodeError: 'ascii' codec can't encode character '\u5f90'...
fname.encode('ascii', 'replace')
# b'?'
fname.encode('ascii', 'ignore')
# b''
fname.encode('ascii', 'xmlcharrefreplace')
# b'徐'
fname.encode('ascii', 'backslashreplace')
# b'\\u5f90'
相關(guān)文章
python matplotlib 注釋文本箭頭簡(jiǎn)單代碼示例
這篇文章主要介紹了python matplotlib 注釋文本箭頭簡(jiǎn)單代碼示例,具有一定借鑒價(jià)值。2018-01-01Python日志打印里logging.getLogger源碼分析詳解
在本篇文章里小編給大家整理的是一篇關(guān)于Python logging.getLogger源碼分析的相關(guān)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。2021-01-01基于Django?websocket實(shí)現(xiàn)視頻畫(huà)面的實(shí)時(shí)傳輸功能(最新推薦)
Django?Channels?是一個(gè)用于在?Django框架中實(shí)現(xiàn)實(shí)時(shí)、異步通信的擴(kuò)展庫(kù),本文給大家介紹基于Django?websocket實(shí)現(xiàn)視頻畫(huà)面的實(shí)時(shí)傳輸案例,本案例是基于B/S架構(gòu)的視頻監(jiān)控畫(huà)面的實(shí)時(shí)傳輸,使用django作為服務(wù)端的開(kāi)發(fā)框架,需要的朋友可以參考下2023-06-06python爬蟲(chóng)請(qǐng)求頁(yè)面urllib庫(kù)詳解
這篇文章主要介紹了python爬蟲(chóng)請(qǐng)求頁(yè)面urllib庫(kù)詳解,python3將urllib和urllib2模塊整合并命名為urllib模塊,urllib模塊有多個(gè)子模塊,各有不同的功能,需要的朋友可以參考下2023-07-07python?HTTP協(xié)議相關(guān)庫(kù)requests urllib基礎(chǔ)學(xué)習(xí)
這篇文章主要介紹了python?HTTP協(xié)議相關(guān)庫(kù)requests urllib基礎(chǔ)學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06Python實(shí)現(xiàn)統(tǒng)計(jì)mp4/avi視頻的時(shí)長(zhǎng)
moviepy是一個(gè)用于處理視頻和音頻的Python庫(kù),它提供了一組功能豐富的工具,所以本文將利用它實(shí)現(xiàn)統(tǒng)計(jì)mp4/avi視頻的時(shí)長(zhǎng),希望對(duì)大家有所幫助2023-07-07tensorflow 環(huán)境變量設(shè)置方式
今天小編就為大家分享一篇tensorflow 環(huán)境變量設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02基于Python實(shí)現(xiàn)文件的壓縮與解壓縮
在日常工作中,除了會(huì)涉及到使用Python處理文本文件,有時(shí)候還會(huì)涉及對(duì)壓縮文件的處理。本文為大家總結(jié)了利用Python可以實(shí)現(xiàn)的幾種文件壓縮與解壓縮實(shí)現(xiàn)代碼,需要的可以參考一下2022-03-03Python實(shí)現(xiàn)批量填補(bǔ)遙感影像的無(wú)效值NoData
這篇文章主要為大家介紹了如何基于Python中ArcPy模塊,對(duì)大量柵格遙感影像文件批量進(jìn)行無(wú)效值(NoData值)填充的方法,感興趣的小伙伴可以了解一下2023-06-06