python中快速進(jìn)行多個(gè)字符替換的方法小結(jié)
先給出結(jié)論:
- 要替換的字符數(shù)量不多時(shí),可以直接鏈?zhǔn)?code>replace()方法進(jìn)行替換,效率非常高;
- 如果要替換的字符數(shù)量較多,則推薦在 for 循環(huán)中調(diào)用
replace()
進(jìn)行替換。
可行的方法:
1. 鏈?zhǔn)絩eplace()
string.replace().replace()
1.x 在for
循環(huán)中調(diào)用replace()
「在要替換的字符較多時(shí)」
2. 使用string.maketrans
3. 先 re.compile 然后 re.sub
……
def a(text): chars = "&#" for c in chars: text = text.replace(c, "\\" + c) def b(text): for ch in ['&','#']: if ch in text: text = text.replace(ch,"\\"+ch) import re def c(text): rx = re.compile('([&#])') text = rx.sub(r'\\\1', text) RX = re.compile('([&#])') def d(text): text = RX.sub(r'\\\1', text) def mk_esc(esc_chars): return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s]) esc = mk_esc('&#') def e(text): esc(text) def f(text): text = text.replace('&', '\&').replace('#', '\#') def g(text): replacements = {"&": "\&", "#": "\#"} text = "".join([replacements.get(c, c) for c in text]) def h(text): text = text.replace('&', r'\&') text = text.replace('#', r'\#') def i(text): text = text.replace('&', r'\&').replace('#', r'\#')
參考鏈接:
http://stackoverflow.com/questions/3411771/multiple-character-replace-with-python
http://stackoverflow.com/questions/6116978/python-replace-multiple-strings
http://stackoverflow.com/questions/8687018/python-string-replace-two-things-at-once
http://stackoverflow.com/questions/28775049/most-efficient-way-to-replace-multiple-characters-in-a-string
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用python能有所幫在,如果有疑問(wèn)大家可以留言交流。
相關(guān)文章
python?numpy?中l(wèi)inspace函數(shù)示例詳解
這篇文章主要介紹了python?numpy?中l(wèi)inspace函數(shù),本文我們通過(guò)示例學(xué)習(xí)了linspace函數(shù),如果你熟悉NumPy,一定也注意到還有np.arange函數(shù),兩者最大差異是,linspace能夠精確控制終止值終值,而arange能夠更直接地控制序列中值之間的增量,需要的朋友可以參考下2023-03-03Python截圖的五個(gè)方法實(shí)例總結(jié)
學(xué)習(xí)一門(mén)語(yǔ)言最好的方法便是實(shí)踐,想要拿Python寫(xiě)一個(gè)截圖工具,下面這篇文章主要給大家介紹了關(guān)于Python截圖的五個(gè)方法,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12關(guān)于Python的文本文件轉(zhuǎn)換編碼問(wèn)題
這篇文章主要介紹了關(guān)于Python的文本文件轉(zhuǎn)換編碼問(wèn)題,編程過(guò)程中,經(jīng)成會(huì)遇到字符編碼的問(wèn)題,需要的朋友可以參考下2023-04-04Python基礎(chǔ)之語(yǔ)法錯(cuò)誤和異常詳解
Python有兩種錯(cuò)誤很容易辨認(rèn):語(yǔ)法錯(cuò)誤和異常.本文就給大家詳細(xì)介紹一下Python錯(cuò)誤和異常,對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助哦,需要的朋友可以參考下2021-05-05Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解
二叉樹(shù)是最基本的數(shù)據(jù)結(jié)構(gòu),這里我們?cè)赑ython中使用類的形式來(lái)實(shí)現(xiàn)二叉樹(shù)并且用內(nèi)置的方法來(lái)遍歷二叉樹(shù),下面就讓我們一起來(lái)看一下Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解2016-05-05