tags:

views:

178

answers:

6

Hi there!

I am searching for an 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.

This is less a question, than having fun to find a short Python function ;-)

+12  A: 
>>> 'foobar'.encode('rot13')
'sbbone'

(I've heard rumors this doesn't work in Python 3.x though.)

Amber
Rumor approved. `rot13` definitely isn't an available codec in Python3.
poke
Nice one anyway. Really neat. Hopefully they removed it from Python 3. Rot13 codec is everything but usefull in a standard lib.
e-satis
A: 

Try this:

import codecs
codecs.encode("text to be rot13()'ed", "rot13")
Barrest
The `.encode` method is included as part of string objects and doesn't need to be specifically imported.
Amber
+5  A: 

The maketrans and translate functions in the string module are handy for this type of thing. Of course, the encode method in Amber's response is even handier for this specific case.

Here's a general solution:

import string

def make_rot_n(n):
 lc = string.lowercase
 trans = string.maketrans(lc, lc[n:] + lc[:n])
 return lambda s: string.translate(s, trans)

rot13 = make_rot_n(13)

rot13('foobar')
# 'sbbone'
ars
+6  A: 

Here's a maketrans/translate solution

import string #fixed typo was using
rot13 = string.maketrans( \
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", \
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'
Paul Rubel
No need for backslashes.
Mark Tolonen
`import` not `using`.
Mark Tolonen
This is the shortest and its available under 3.0 :-)
Sven Walter
Backslashes (`\\`) aren't needed inside parenthesis.
KennyTM
A: 

its very simple

import codecs
codecs.encode('foobar', 'rot13')
>> 'sbbone'
nazmul hasan
+1  A: 

/usr/lib/python/this.py

def rot13(s):
    d = {}
    for c in (65, 97):
        for i in range(26):
            d[chr(i+c)] = chr((i+13) % 26 + c)
    return "".join([d.get(c, c) for c in s])
Artur Gaspar