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: ###-####