A quick way to make multiple character substitutions in Python summary _python

Source: Internet
Author: User

First the conclusion:

    1. The number of characters to be replaced is not long, the direct chain method can be replace() replaced, the efficiency is very high;
    2. 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.

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.