How to replace multiple characters in python

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.