2to3 and maketrans

Martin v. Loewis martin at v.loewis.de
Thu Mar 3 18:46:37 EST 2011


Am 03.03.2011 07:58, schrieb Gregory Ewing:
> What is the recommended way to write code for 2.7 using
> maketrans() on text strings in such a way that it will
> convert correctly using 2to3?

That depends on how you chose to represent text in 2.7.
The recommended way for that (also with 3.x in mind)
is that you should use Unicode strings to represent text.

Now, unicode strings support translation tables mapping
Unicode ordinals to Unicode strings in both 2.x and 3.x,
so I suggest you just don't use maketrans at all.

To give an example,

print u"hallo".translate({97:u'e'})

works fine in 2.x, and will work fine in 3.x when put
through 2to3 (which will convert the print and the unicode
literals).

If you chose to represent strings as bytes in 2.x, the
answer will be different.

Regards,
Martin



More information about the Python-list mailing list