rot13 in a more Pythonic style?

Rob Wolfe rw at smsnet.pl
Wed Feb 14 16:53:03 EST 2007


"Andy Dingley" <dingbat at codesmiths.com> writes:

> 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.

It looks to me like a good place to use closure and dictionaries.
I would write it this way:

def rot(step):
    import string
    rot_char = lambda a,c,step=step: chr((((ord(c) - ord(a)) + step) % 26) + ord(a))
    make_dict = lambda a,s: dict([(x, rot_char(a, x)) for x in s])
    d = make_dict('a', string.ascii_lowercase)
    d.update(make_dict('A', string.ascii_uppercase))
    def f(s):
        return "".join([d.get(c) or c for c in s])
    return f

>>> rot13 = rot(13)
>>> rot13('Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt')
'Florix Grabundae, Splundig vur thrigg'
>>> rot_13 = rot(-13)
>>> rot_13('Florix Grabundae, Splundig vur thrigg')
'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'

-- 
HTH,
Rob



More information about the Python-list mailing list