Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
svenwltr Avatar asked Jul 17 '10 00:07

svenwltr


People also ask

How do I decrypt rot13 in Python?

To decode a rot13 encoded string, say s , simply take rot13 of the string once again, i.e. compute rot13(s) . If you are not familiar how to compute rot13 in python, try googling a bit and you'll surely find one.

What is rot in Python?

The following function rot(s, n) encodes a string s with ROT- n encoding for any integer n , with n defaulting to 13. Both upper- and lowercase letters are supported. Values of n over 26 or negative values are handled appropriately, e.g., shifting by 27 positions is equal to shifting by one position.

How do you write rot13 code in Python?

ROT13 = Rotate the string to be encrypted by 13 positions (modulo 26) in the alphabet of 26 characters. If you want to encrypt a string, shift each character forwards by 13 positions in the alphabet. If you move past the last character “z”, you start over at the first position in the alphabet “a”.

What is rot13 used for?

ROT13 ("rotate by 13 places", usually hyphenated ROT-13) is a simple Caesar cipher used for obscuring text by replacing each letter with the letter thirteen places down the alphabet.


2 Answers

It's very simple:

>>> import codecs >>> codecs.encode('foobar', 'rot_13') 'sbbone' 
like image 110
Nazmul Hasan Avatar answered Sep 24 '22 04:09

Nazmul Hasan


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!' 
like image 25
Paul Rubel Avatar answered Sep 20 '22 04:09

Paul Rubel