Introduction to how to replace multiple characters in Python

Source: Internet
Author: User
the conclusion is given first:
The number of characters to be replaced can be directly linked

Replace ()

method to replace, the efficiency is very high;
If the number of characters to replace is large, it is recommended to call in the For loop

Replace ()

be replaced.
Possible methods:
1. Chained replace ()

String.Replace (). Replace ()


1.x in

For

Calling in Loops

Replace ()

"When there are more characters to replace"
2. Using String.maketrans
3. Re.compile First 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 lamb Da 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 = Tex T.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 ' \# ') 

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.