简体   繁体   中英

Why is ROT 13 displaying g in spaces?

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM