1. String. maketrans set the String Conversion rule table (translation table) allchars = string. maketrans ('','') # All strings, that is, the strings are not replaced.
Atob = string. maketrans ('A', 'B') # convert character a to character B
2. The translate function replaces and deletes strings. The first parameter is the String Conversion rule table, and the second parameter is the string to be deleted. For example, to replace all E in string s with a, and delete all oatob = string. maketrans ('E', 'A ')
S = 'Hello python'
Print S. Translate (atob, 'O ')
Output result:
Hall pythn
3. If we use allchars = string. maketrans ('','')
K = allchars. Translate (allchars, 'A ')
Allchars indicates all strings, and K indicates removing character a from all strings, that is, all characters except a. Therefore, when we call the following method:
S = 'abc'
Print S. Translate (allchars, K)
Literally, the output "except any character that is not character a in string s" means that only character a is output, so the output result is:
A
4. Now, it is easy to understand the following function: Import string
Def Translator (FRM = '', To ='', delete = '', keep = none ):
If Len (to) = 1:
To = to * Len (FRM)
Trans = string. maketrans (FRM,)
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:
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 :###-####