ArticleDirectory
- 1. String. maketrans set the String Conversion rule table (translation table)
- 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 o
- 3. If we use
- 4. Now, it is not difficult to understand the following function.
1. String. maketrans set the String Conversion rule table (translation table) Allchars = String. maketrans ( '' , '' ) # All strings, that is, do not replace strings
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 o Atob = 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'
PrintS. 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. Import String
Def Translator (FRM = '' , = '' , Delete = '' , Keep = None ):
If Len () = 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, = ' # ' )
Print Digits_to_hash ( ' Chris Perkins: 224-7992 ' )
Output result:
2247992
Chris Perkins :###-####
Python daily delicious series (total)
Python daily delicious (7)-join string (join %)
Python daily delicious (8)-character inversion in strings
Python delicious everyday (9)-translator
Python daily delicious (10)-Division tips
Python delicious everyday (11)-cute and case-sensitive
...