Caesar Cipher in Python

The Caesar Cipher is a simple encryption technique where each letter in a string is shifted by a fixed number of positions in the alphabet. When a letter goes past 'z', it wraps around to 'a'.

For example, if we have the string "hello" and shift by 3 positions, 'h' becomes 'k', 'e' becomes 'h', and so on, resulting in "khoor".

Algorithm Steps

To implement the Caesar cipher, we follow these steps ?

  • Convert each character to its position in the alphabet (0-25)

  • Add the shift value k to this position

  • Use modulo 26 to handle wrapping around the alphabet

  • Convert back to a character and return the result

Implementation

Using a Helper Function

Here's a clean implementation using a nested helper function ?

class Solution:
    def solve(self, s, k):
        def shift(c):
            i = ord(c) - ord('a')
            i += k
            i %= 26
            return chr(ord('a') + i)
        
        return "".join(map(shift, s))

# Test the implementation
ob = Solution()
result = ob.solve("hello", 3)
print(f"Input: 'hello', shift: 3")
print(f"Output: {result}")
Input: 'hello', shift: 3
Output: khoor

Alternative Implementation

Here's a more direct approach without using a class ?

def caesar_cipher(text, shift):
    result = ""
    for char in text:
        # Calculate new position
        shifted_pos = (ord(char) - ord('a') + shift) % 26
        # Convert back to character
        result += chr(ord('a') + shifted_pos)
    return result

# Test with different examples
print(caesar_cipher("hello", 3))
print(caesar_cipher("xyz", 3))
print(caesar_cipher("abc", 25))
khoor
abc
zab

How It Works

The key insight is using ord() and chr() functions:

  • ord(c) - ord('a') converts a letter to its alphabet position (0-25)

  • Adding the shift value moves the position forward

  • % 26 ensures wrapping around the alphabet

  • chr(ord('a') + i) converts back to a character

Conclusion

The Caesar cipher demonstrates fundamental string manipulation and modular arithmetic in Python. The modulo operation ensures proper alphabet wrapping, making this a clean and efficient implementation for basic text encryption.

Updated on: 2026-03-25T10:16:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements