1. string. maketrans set the string Conversion rule table (translation table)
Copy codeThe Code is as follows:
Allchars = string. maketrans ('','') # All strings, that is, the strings are not replaced.
ATob = string. maketrans ('A', 'B') # convert character a to character B
2. Use the translate function to replace and delete 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 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
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
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 not difficult 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,)
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 :###-####