Caesar Cipher Implementation in Python: Encrypted Text not Displaying Correctly
This Python code aims to implement the Caesar cipher, which shifts characters based on user input. However, the resulting cipher text only displays the last shifted character instead of the entire encrypted string. The code provided is as follows:
<code class="python">plainText = raw_input("What is your plaintext? ") shift = int(raw_input("What is your shift? ")) def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift if stayInAlphabet > ord('z'): stayInAlphabet -= 26 finalLetter = chr(stayInAlphabet) cipherText += finalLetter print "Your ciphertext is: ", cipherText return cipherText caesar(plainText, shift)</code>
Analysis
The issue lies within the loop that processes each character in the plaintext. Instead of appending all the shifted characters to the cipherText variable, the code only updates it with the last shifted character. To correct this, the original cipherText variable should be declared before the character processing loop.
Pythonic Implementation
An optimized Caesar cipher implementation can be achieved using Python's string manipulation methods:
<code class="python">def caesar(plaintext, shift): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[shift:] + alphabet[:shift] table = string.maketrans(alphabet, shifted_alphabet) return plaintext.translate(table)</code>
By utilizing string.maketrans() and str.translate(), the entire plaintext string can be encrypted with a single operation, resulting in improved performance and code readability.
The above is the detailed content of Why is my Python Caesar Cipher only displaying the last shifted character?. For more information, please follow other related articles on the PHP Chinese website!