Python Translator Use instance _python

Source: Internet
Author: User
Tags translate function
1.string.maketrans Set string conversion rules table (translation table)
Copy Code code as follows:

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


2.translate function for string substitution and deletion, the first argument is the string conversion rules table (translation table) and the second is the string to be deleted. For example, to replace all the E in the string s with a, and to remove all O
Copy Code code as follows:

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

Output results:
Hall PYTHN


3. If we use this
Copy Code code as follows:

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

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

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

In the literal sense, the output "string s is to remove any character that is not a character", that is, only the character A is output, so the output is:
A

4. Now, it's not hard to understand the following function
Copy Code code 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 Code code 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 results:
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.