Rot13 function but the code can't translate if letter clue is over 122

Question:

The answers come one by one but if the value is over 122 then the following code doesn’t work.

def rotate_word13(line, num):
    for x in line:
        a = ord(x)
        a = ord(x) + num
        print(a)

        if a >= 122:
            e = a - 122
            print(e)
            x = chr(e)
            print(x)
        else:
            x = chr(a)
            print(x)

rotate_word13("hello", 13)
rotate_word13("r", 13)

Here is the result. As you can see it works only if ord is less than 122 after it’s been subtracted.

117
u
114
r
121
y
121
y
124
2
127
5
Asked By: Mahir Hasan

||

Answers:

You seem to be trying to implement the ROT13 cypher.

You need to take account of upper- and lower-case letters. Simply find where the letter is in an ordered list of letters, add 13 to that index and then modulo by 26.

Like this:

from string import ascii_lowercase as L, ascii_uppercase as U

def rot13(s):
    r = []
    for c in s:
        if (i := U.find(c)) >= 0:
            r.append(U[(i + 13) % 26])
        elif (i := L.find(c)) >= 0:
            r.append(L[(i + 13) % 26])
        else:
            r.append(c)
    return ''.join(r)

print(rot13('Why did the chicken cross the road'))

Output:

Jul qvq gur puvpxra pebff gur ebnq
Answered By: Fred
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.