First the conclusion:
- The number of characters to be replaced is not long, the direct chain method can be
replace() replaced, the efficiency is very high;
- If there are more characters to replace, it is recommended that the substitution be called in the For Loop
replace() .
Feasible method:
1. Chain type replace ()
String.Replace (). Replace ()
1.x for calling replace() "when more characters are to be replaced" in the loop
2. Use of 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 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 E LSE C for C in S])
ESC = Mk_esc (' &# ')
def e (text):
ESC (text)
def f (text):
text = Text.replac E (' & ', ' \& '). 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 ' \# ')
Reference Links:
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
Summarize
The above is the entire content of this article, I hope that the content of this article for you to learn or use Python can help in, if there are questions you can message exchange.