Summary of methods for quickly performing multiple character substitutions in python
- 2020-05-17 05:53:07
- OfStack
First, give the conclusion:
The number of characters to replace is small and can be chained directlyreplace()
The method can be replaced with high efficiency.
If you have a large number of characters to replace, it is recommended to call in the for loop
replace()
Make the substitution.
Possible methods:
1. Chain replace ()
string.replace().replace()
1. x in
for
Call in loop
replace()
"When there are too many characters to replace"
2. Use string. maketrans
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'\#')
Reference:
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
conclusion
The above is the whole content of this article, I hope the content of this article can help you to learn or use python, if you have any questions, you can leave a message to communicate.