Python Translator Usage Examples

Source: Internet
Author: User
1.string.maketrans Set string conversion rules table (translation table)
Copy CodeThe code is as follows:


Allchars = String.maketrans (', ') #所有的字符串, that is, do not replace the string
Atob = String.maketrans (' A ', ' B ') #将字符a转换为字符b



2.translate function for string substitution and deletion, the first argument is the String conversion rule table (translation table), and the second parameter is the string to delete. For example, to replace all E in the string s with a, and to delete all O
Copy CodeThe code is as follows:


Atob = String.maketrans (' e ', ' a ')
s = ' Hello python '
Print s.translate (Atob, ' O ')


Output Result:
Hall PYTHN


3. If we use this
Copy CodeThe code is as follows:


Allchars = String.maketrans (",")
K = allchars.translate (Allchars, ' a ')


Allchars represents all the strings, and K means to remove the character a from all the strings, that is, all the characters except a, so when we call the following method:
Copy CodeThe code is as follows:


s = ' abc '
Print S.translate (Allchars, K)


The literal meaning is that the output "string S" removes any characters that are not character a ", that is, only the character A is output, so the output is:
A

4. Now, it's easy to understand the following function
Copy CodeThe code is as follows:


Import string
def translator (frm= ", to=", delete= ", Keep=none):
If Len (to) = = 1:
to = to * Len (frm)
trans = String.maketrans (frm, to)
If keep is not None:
Allchars = String.maketrans (",")
Delete = Allchars.translate (Allchars, keep.translate (allchars, delete))
def translate (s):
Return S.translate (trans, delete)


Return Translate call:
Copy CodeThe code is as follows:


Digits_only = Translator (keep=string.digits)
Print digits_only (' Chris perkins:224-7992 ')

Digits_to_hash = Translator (frm=string.digits, to= ' # ')
Print Digits_to_hash (' Chris perkins:224-7992 ')


Output Result:
2247992
Chris Perkins: ###-####
  • 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.