String comparison question

Alex Martelli aleaxit at yahoo.com
Mon Mar 20 05:20:50 CET 2006


Michael Spencer <mahs at telcopartners.com> wrote:

> Olivier Langlois wrote:
> > Hi Michael!
> > 
> > Your suggestion is fantastic and is doing exactly what I was looking
> > for! Thank you very much.
> > There is something that I'm wondering though. Why is the solution you
> > proposed wouldn't work with Unicode strings?
> > 
> Simply, that str.translate with two arguments isn't implemented for
> unicode strings.  I don't know the underlying reason, or how hard it would
> be to change.

A Unicode's string translate takes a dict argument -- you delete
characters by mapping their ord(...) to None. For example:

>>> u'banana'.translate({ord('a'):None})
u'bnn'

That is in fact much handier, when all you want to do is deleting some
characters, than using string.maketrans to create a "null" translation
table and passing as the 2nd argument the string of chars to delete.

With unicode .translate, you can also translate a character into a
STRING...:

>>> u'banana'.translate({ord('a'):u'ay'})
u'baynaynay'

...which is simply impossible with plainstring's .translate.


Alex



More information about the Python-list mailing list