Filtering out non-readable characters

George Sakkis gsakkis at rutgers.edu
Sat Jul 16 20:48:20 EDT 2005


"Peter Hansen" <peter at engcorp.com> wrote:

> Jp Calderone wrote:
> > On Sat, 16 Jul 2005 19:01:50 -0400, Peter Hansen <peter at engcorp.com> wrote:
> >> George Sakkis wrote:
> >>>>>> identity = string.maketrans('','')
> >>
> >> Wow!  That's handy, not to mention undocumented.  (At least in the
> >> string module docs.)  Where did you learn that, George?
> >>
> > http://python.org/doc/lib/node109.html
>
> Perhaps I was unclear.  I thought it would be obvious that I knew where
> to find the docs for maketrans(), but that the particular behaviour
> shown (i.e. arguments of '' having that effect) was undocumented in that
> page.
>
> -Peter

Actually I first read about this in the Cookbook; there are two or three recipes related to
string.translate. As for string.maketrans, it doesn't do anything special for empty string
arguments:

      maketrans( from, to)

Return a translation table suitable for passing to translate() or regex.compile(), that will map
each character in from into the character at the same position in to; from and to must have the same
length.

So if from and to are empty, maketrans will map zero characters, hence the identity. It's not the
only way to get the identity translation table by the way:
>>> string.maketrans('', '') == string.maketrans('a', 'a') == string.maketrans('hello', 'hello')
True

George





More information about the Python-list mailing list