Search code examples
pythonstringcaesar-cipher

How to format output of Ceaser Cipher program python


I am trying to make a simple Ceaser cipher and have it mostly working the way I want. Except, I want to only shift the letters in the message that are uppercase and keep the lowercase letters the same. For example, if the message is "HeLLo" the program should only shift "H LL" and keep "e o" the same. As shown below.

Current output:

Message: HeLLo
Shift: 1
IFMMP

Desired output:

Message: HeLLo
Shift: 1
IeMMo

The code:

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)

Solution

  • You could add ch != ch.lower() condition to check that the character is not a lowercase character and encrypt it only when it isn't a lowercase character.

    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)