python中快速進(jìn)行多個字符替換的方法小結(jié)
先給出結(jié)論:
- 要替換的字符數(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()
「在要替換的字符較多時」
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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學(xué)習(xí)或者使用python能有所幫在,如果有疑問大家可以留言交流。
相關(guān)文章
python?numpy?中l(wèi)inspace函數(shù)示例詳解
這篇文章主要介紹了python?numpy?中l(wèi)inspace函數(shù),本文我們通過示例學(xué)習(xí)了linspace函數(shù),如果你熟悉NumPy,一定也注意到還有np.arange函數(shù),兩者最大差異是,linspace能夠精確控制終止值終值,而arange能夠更直接地控制序列中值之間的增量,需要的朋友可以參考下2023-03-03關(guān)于Python的文本文件轉(zhuǎn)換編碼問題
這篇文章主要介紹了關(guān)于Python的文本文件轉(zhuǎn)換編碼問題,編程過程中,經(jīng)成會遇到字符編碼的問題,需要的朋友可以參考下2023-04-04Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解
二叉樹是最基本的數(shù)據(jù)結(jié)構(gòu),這里我們在Python中使用類的形式來實(shí)現(xiàn)二叉樹并且用內(nèi)置的方法來遍歷二叉樹,下面就讓我們一起來看一下Python實(shí)現(xiàn)二叉樹結(jié)構(gòu)與進(jìn)行二叉樹遍歷的方法詳解2016-05-05