-1

I've a rot13 encoded string in python and I've to decode it:

"Gur dhvpx oebja sbk whzcrq bire gur ynml qbt"

Is it possible to do in python? I can't find any method to do it.

Please help!

This is what I've tried:

s = "Gur dhvpx oebja sbk whzcrq bire gur ynml qbt"
s1 = ""
for i in range(len(s)):
    c = s[i]
    if c >= 'a' and c <= 'm': c += 13
    elif c > 'A' and c < 'M': c += 13
    elif c >= 'n' and c < 'z': c -= 13
    elif c >= 'N' and c <= 'Z': c -= 13
    s1 += c
    print(c)
print(s1)
ChrisF
  • 134,786
  • 31
  • 255
  • 325
user8852303
  • 27
  • 1
  • 5

2 Answers2

2

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. I googled and found a solution that works pretty well : https://stackoverflow.com/a/3269756/3293087 [Note that it works only on python2 and not python3 since string.maketrans was removed from python3.]

I'll write the code here for completeness :

# Python 2 solution
import string
rot13Table = string.maketrans( 
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", 
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
rot13 = lambda s : string.translate(s, rot13Table)

print rot13("Hello World!") 
# Outputs "Uryyb Jbeyq!"

Note : I'm not going to write the decoded string corresponding to what the OP originally posted, since its quite offensive and homophobic. Anyone interested can do it themselves.

Update : I also found a solution that works for python 2 & 3 both from this SO answer. It turns out there is a builtin rot13 encoder in python in the codecs module :

# Python 2 & 3 compatible
import codecs
rot13 = lambda s : codecs.getencoder("rot-13")(s)[0]

# Answer
rot13("Gur dhvpx oebja sbk whzcrq bire gur ynml qbt")

Update 2 : Since the OP is adamant to know the answer and does not seem to have python installed, I have a created JS solution https://codepen.io/anon/pen/zPYVQP. Others please proceed with caution.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Abhishek Kedia
  • 867
  • 6
  • 17
0
utf8 = str.maketrans(
    # this are the related alphabets
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm",
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
)  
print(str.translate("Gur dhvpx oebja sbk whzcrq bire gur ynml qbt", utf8))
Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82