python中快速進行多個字符替換的方法小結
先給出結論:
- 要替換的字符數(shù)量不多時,可以直接鏈式
replace()方法進行替換,效率非常高;
- 如果要替換的字符數(shù)量較多,則推薦在 for 循環(huán)中調(diào)用
replace()進行替換。
可行的方法:
1. 鏈式replace()
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
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學習或者使用python能有所幫在,如果有疑問大家可以留言交流。
相關文章
python?numpy?中l(wèi)inspace函數(shù)示例詳解
這篇文章主要介紹了python?numpy?中l(wèi)inspace函數(shù),本文我們通過示例學習了linspace函數(shù),如果你熟悉NumPy,一定也注意到還有np.arange函數(shù),兩者最大差異是,linspace能夠精確控制終止值終值,而arange能夠更直接地控制序列中值之間的增量,需要的朋友可以參考下2023-03-03
Python實現(xiàn)二叉樹結構與進行二叉樹遍歷的方法詳解
二叉樹是最基本的數(shù)據(jù)結構,這里我們在Python中使用類的形式來實現(xiàn)二叉樹并且用內(nèi)置的方法來遍歷二叉樹,下面就讓我們一起來看一下Python實現(xiàn)二叉樹結構與進行二叉樹遍歷的方法詳解2016-05-05

