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