How to Implement a Caesar Cipher for Basic Encryption
How to Implement a Caesar Cipher for Basic Encryption
How to Implement a Caesar Cipher for Basic Encryption
I want to create a simple Caesar cipher to shift characters in a string by a specific number of places. How can I do this?
solveurit24@gmail.com Changed status to publish February 16, 2025
A Caesar cipher shifts each letter in the string by a certain number of places down the alphabet.
Code Example:
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isalpha():
shifted = chr(ord(char.lower()) + shift)
if shifted > 'z':
shifted = chr(ord(shifted) - 26)
encrypted_char = shifted.upper() if char.isupper() else shifted
encrypted.append(encrypted_char)
else:
encrypted.append(char)
return ''.join(encrypted)
# Example usage
print(caesar_cipher("Hello, World!", 3)) # Output: "Khoor, Zruog!"This function shifts each letter by the specified number of places, wrapping around if necessary, and maintains the case of the original text.
solveurit24@gmail.com Changed status to publish February 16, 2025