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.
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.
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.
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”.
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.
It's very simple:
>>> import codecs >>> codecs.encode('foobar', 'rot_13') 'sbbone'
maketrans()
/translate()
solutions…
import string rot13 = string.maketrans( "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm") string.translate("Hello World!", rot13) # 'Uryyb Jbeyq!'
rot13 = str.maketrans( 'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz', 'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm') 'Hello World!'.translate(rot13) # 'Uryyb Jbeyq!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With