rot13 in a more Pythonic style?

Neil Cerutti horpner at yahoo.com
Wed Feb 14 11:23:04 EST 2007


On 2007-02-14, Andy Dingley <dingbat at codesmiths.com> wrote:
> I'm trying to write rot13, but to do it in a better and more
> Pythonic style than I'm currrently using. What would  you
> reckon to the following pretty ugly thing?   How would you
> improve it?  In particular, I don't like the way a three-way
> selection is done by nesting two binary selections. Also I
> dislike stating the same algorithm twice, but can't see how to
> parameterise them neatly.
>
> Yes, I know of .encode() and .translate().

str.translate is what I'd do.

import string
rot13table = string.maketrans(
  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 
  'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM')

print 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'.translate(rot13table)

> No, I don't actually need rot13 itself, it's just a convenient
> substitute example for the real job-specific task. No, I don't
> have to do it with lambdas, but it would be nice if the final
> function was a lambda.

How would it being a lambda help you?

-- 
Neil Cerutti



More information about the Python-list mailing list