Python's handling of strings is more efficient and has many methods. Maketrans and translate two methods are used many, but the specific how to use often can't remember.
Let's look at these two methods first:
1.s.translate (TABLE,STR) removes the characters that str contains from the string s, and the remaining strings are replaced by the character mappings in the table. Table can be interpreted as a conversion table, comparing ' a ', ' a ', ' B ', ' B '.
2.tabel = String.maketrans (' s1 ', ' s2 ') S1 and S2 must be the same length, Maketrans generate a conversion table, if there is S1 in S, then replace with S2, the conversion table is a character one by one, there is no need to include all
A few examples
1 Importstring2 3s ='HelloWorld, 0001111'4 5Table = String.maketrans ("',"')#no mapping, preserving the original string6S.translate (table)#Hello World, 00011117S.translate (table,'hello000)'#World , 11118 9Table = String.maketrans ('ABCDEFGH','ABCDEFGH')TenS.translate (table)#hello,world,0001111 OneS.translate (table,' World')#hello,0001111
We can now talk about makerans,translate wrapping up and forming a factory function that returns closures (print is the factory function)
1 Importstring2 defTranslator (frm ="', to="', delete="', keep =None):3 ifLen (To) = = 1:4to = to *len (frm)5trans =String.maketrans (frm, to)6 ifKeep is notNone:7Allchars = String.maketrans ("',"')8Delete =allchars.translate (Allchars, keep.translate (allchars, delete))9 defTranslate (s):Ten returns.translate (trans, delete) One returnTranslate
The last use of a function is a closure, which is a function that has access to a variable in another function scope. A common way to create closures is to create another function inside one function:
1 def Make_adder (addend): 2 def return augend + addend3 return adder
Execution P = make_addr (23) will produce a closure of the inner layer function addr, which references the name Addend internally, and Addend is bound to the value 23, and the execution p (100) eventually returns 123.
Now we have closed all possibilities behind a suggested interface.
>>>digits_only = Translator (keep = string.digits)
>>>digits_only (' Chris perkins:224-7992 ')
' 2247992 '
Removing elements that belong to a character set is also very simple:
>>>no_digits = Translator (delete = string.digits)
>>>no_digits (' Chris perkins:224-7992 ')
' Chris perkings:-'
You can also replace:
>>>digits_to_hash = Translator (from = string.digits, to = ' # ')
>>>digits_to_hash (' Chris perkins:224-7992 ')
' Chris Perkins: ###-#### '
When delete and keep have overlapping parts, the delete parameter takes precedence
>>>trans = Translator (delete = ' ABCD ', Kepp = ' cdef ')
>>>trans (' ABCDEFG ')
' EF '
In fact, you can add some exceptions in more detail to deal with the situation of delete,keep at the same time.
Application of closures in Python, translate and Maketrans methods