Converting some characters of a string in python to a specific character is often used in the Maketrans () function in the string library, as well as the translate () function. But these two functions are abstract: The Maketrans function produces an object that is a table that is not very friendly to beginners. The first parameter required by the tranlate (table, DeleteValue) function is a table structure, which is the return value of Maketrans, and DeleteValue is the character to be deleted. This second parameter is awkward: a translate function, and sometimes some characters can be deleted. And the use of the process, often two functions are used together, rather than directly into a function, more convenient.
In the process of using translator, we often need four parameters: the source string, the target string, the one by one correspondence, the character to be preserved, the character to delete. So, create a new function directly with these four parameters as input:
Import stringdef Translator (origin= ", target=", delete= ", keep="): "" " Keep is primer than delete but Keep without chars in delete "" " If Len (target) = = 1: target *= Len (origin) assert (Len (target) ==len ( Origin)) if keep! = ': allchars = String.maketrans (', ') keep = Keep.translate (allchars,delete) Delete = Allchars.translate (allchars,keep) trans = String.maketrans (origin,target) def translate (SSS): return Sss.translate (trans,delete) return translate
The translator function at this point requires that we first construct the function and then call the returned function.
Like what
>>>trans = Translator (delete= ' ABCD ', keep= ' cdef ')
>>>trans (' Abcdefgll ')
' EF '
You should be aware of the relationship between delete and keep.
>>>digit2hash = Translator (origin = string.digits,target= ' @ ')
>>>digit2hash (' myjiayan:368-346-290 ')
' Myjiayan: @@@[email protected]@@[email protected]@@ '
This is a good translator function.
[note] Creating a string in Python translator