Как отформатировать вывод программы Ceaser Cipher Python

Я пытаюсь сделать простой шифр Цезаря, и он в основном работает так, как я хочу. За исключением того, что я хочу только сдвинуть буквы в сообщении, которые являются прописными, и оставить строчные буквы одинаковыми. Например, если сообщение "HeLLo", программа должна сдвинуть только "H LL" и оставить "e o" без изменений. Как показано ниже.

Текущий выход:

Message: HeLLo
Shift: 1
IFMMP

Желаемый результат:

Message: HeLLo
Shift: 1
IeMMo

Код:

plain_text = input("Message: ")
shift = int(input("Shift: "))

def caesar(plain_text, shift): 
  cipher_text = ""
  for ch in plain_text:
    if plain_text.lower():
      plain_text = plain_text

    if ch.isalpha():
      final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
      cipher_text += final_letter
    else:
      cipher_text += ch
  print(cipher_text)
  return cipher_text

caesar(plain_text, shift)

person Alexandro    schedule 19.03.2020    source источник


Ответы (2)


Вы можете добавить условие ch != ch.lower(), чтобы проверить, что символ не является символом нижнего регистра, и зашифровать его, только если он не является символом нижнего регистра.

plain_text = input("Message: ")
shift = int(input("Shift: "))

def caesar(plain_text, shift): 
  cipher_text = ""
  for ch in plain_text:
    if ch.isalpha() and ch != ch.lower():
      final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
      cipher_text += final_letter
    else:
      cipher_text += ch
  print(cipher_text)
  return cipher_text

caesar(plain_text, shift)
person Osama Abdul Rehman    schedule 19.03.2020
comment
Спасибо, это здорово - person Alexandro; 19.03.2020

Я думаю, вам нужно:

def caesar(plain_text, shift):
    return "".join([chr(ord(i)+shift) if i.isupper() else i for i in plain_text])

caesar(plain_text, shift)
person Sociopath    schedule 19.03.2020