Strings’ translate Method

The translate method of strings is quite powerful and flexible. A little factory function, returning a closure, can do wonders for this kind of task

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
Share

Recommended Posts

Leave a Reply

Your email address will not be published. Required fields are marked *