First, the conclusion is given: if there are not many characters to replace, you can directly chain the replace () method for replacement, which is very efficient. if there are many characters to replace, we recommend that you call replace () in the for loop to replace the data. Feasible methods: 1. chain replace () string. replace (). replace () 1. x in the for loop calls replace () "when there are many characters to replace" 2.
Conclusion:
You can directly chain a small number of characters to be replaced
replace()
Method replacement, which is very efficient;
If you want to replace a large number of characters, we recommend that you call
replace()
.
Feasible method:
1. chained replace ()
string.replace().replace()
1. x in
for
Call in loop
replace()
「 When there are many characters to replace 」
2. use string. maketrans
3. First re. compile and then 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 redef 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'\#')
The above describes how to replace multiple characters in python. For more information, see other related articles in the first PHP community!