2011-09-15
Look at the cookbook and see the amazing string. translate function.
You can remove unnecessary strings from the string and map some characters into other characters by using the maketrans ing function.
Cookbook encapsulates the translate code to create a new facade function:
import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
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 >>> digits_only = translator (keep = string. digits)
>>> Digits_only ('chris Perkins: 224-7992 ')
'123'
What's really amazing is that I printed the string. maketrans (frm, to) value, and the results were blank. I haven't figured out how to complete the ing for a long time?
Enter lib/string. py can only see the source code. The maketrans returns a bytes string instead of an empty string when the from to is empty. In windows, nothing can be printed, I followed for a long time. In linux, you can see the complete value of the string, English character numbers and symbols.
Trans = string. maketrans (frm, to) obtains the original 256-byte string, finds the difference set between the keep and delete as the reserved value, finally obtains the string to be retained, and interprets the original string as the required value.