Short rot13 function - Python [closed]

I am searching for a short and cool rot13 function in Python ;-) I've written this function:

def rot13(s):
    chars = "abcdefghijklmnopqrstuvwxyz"
    trans = chars[13:]+chars[:13]
    rot_char = lambda c: trans[chars.find(c)] if chars.find(c)>-1 else c
    return ''.join( rot_char(c) for c in s ) 

Can anyone make it better? E.g supporting uppercase characters.


Solution 1:

It's very simple:

>>> import codecs
>>> codecs.encode('foobar', 'rot_13')
'sbbone'

Solution 2:

maketrans()/translate() solutions…

Python 2.x

import string
rot13 = string.maketrans( 
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", 
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'

Python 3.x

rot13 = str.maketrans(
    'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
    'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
'Hello World!'.translate(rot13)
# 'Uryyb Jbeyq!'

Solution 3:

This works on Python 2 (but not Python 3):

>>> 'foobar'.encode('rot13')
'sbbone'