Caesar Cipher Function in Python: Encrypted Strings
When implementing a Caesar Cipher function in Python, a common issue arises where the final encrypted text displays only the last shifted character. To resolve this, it's necessary to understand the issue causing this behavior.
In the provided code, the loop iterates over each character in the plaintext. For alphabetic characters, it shifts the character's ASCII code based on the provided shift value. However, each shifted character is appended to an empty string named cipherText within the loop. As a result, only the last character is displayed as the encrypted text.
To rectify this issue, the ciphertext must be constructed within the loop and returned once all characters have been processed. This can be achieved by modifying the code as follows:
<code class="python">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 return cipherText</code>
With this modification, the cipherText string is initialized once and all shifted characters are appended to it within the loop. When the function returns, the encrypted string contains all shifted characters, as intended.
The above is the detailed content of Why Does My Caesar Cipher Function in Python Only Display the Last Shifted Character?. For more information, please follow other related articles on the PHP Chinese website!