Why is ROT 13 displaying g in spaces?

209 Views Asked by At

I am writing code that is based on ROT13 Algorithm but when I have the message as "ROT ALGORITHM" it displays as "EBGgNYTBEVGUZ". I am unsure whether the 'g' is wrong since its meant to be a space between ROT and ALGORITHM?

def rot13(message,shift):
    result = "" 

    for i in range(len(message)):
        char = message[i]
        if (char.isupper()):
               result += chr((ord(char) + shift-13) % 26 + 65)
        else:
               result += chr((ord(char) + shift-13) % 26 + 97)
     return result

shift = 13
message = "ROT ALGORITHM"

print("Shift:", shift)    
print(message)
print(rot13(message,shift))
1

There are 1 best solutions below

1
azro On BEST ANSWER

From ROT13 spec, only letters should be affected by the algorithm, here as space is not upper() you go in the else section

You may handle the 2 min usecases : lowercase and uppercase, and just use the alphabet to rotate

from string import ascii_lowercase, ascii_uppercase

def rot13(message, shift):
    result = ""
    for char in message:
        if char in ascii_uppercase:
            result += ascii_uppercase[(ascii_uppercase.index(char) + shift) % 26]
        elif char in ascii_lowercase:
            result += ascii_lowercase[(ascii_lowercase.index(char) + shift) % 26]
        else:
            result += char
    return result