Atbash cipher in Python

The Atbash cipher is a simple substitution cipher where each letter is mapped to its reverse position in the alphabet. In this cipher, 'a' becomes 'z', 'b' becomes 'y', and so on. Let's explore how to implement this cipher in Python.

Understanding the Atbash Cipher

The Atbash cipher works by reversing the alphabet:

  • Original: a b c d e f g h i j k l m n o p q r s t u v w x y z

  • Atbash: z y x w v u t s r q p o n m l k j i h g f e d c b a

The mathematical formula uses ASCII values: N = ord('z') + ord('a'), then for each character, we calculate chr(N - ord(character)).

Implementation

Here's how to implement the Atbash cipher in Python ?

class Solution:
    def solve(self, text):
        N = ord('z') + ord('a')
        return ''.join([chr(N - ord(s)) for s in text])

# Test the implementation
ob = Solution()
print(ob.solve("abcdefg"))
print(ob.solve("hello"))
print(ob.solve("python"))
zyxwvut
svool
kbgsln

Alternative Implementation

Here's a more readable approach using string translation ?

def atbash_cipher(text):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    reversed_alphabet = alphabet[::-1]
    
    translation_table = str.maketrans(alphabet, reversed_alphabet)
    return text.translate(translation_table)

# Test the function
print(atbash_cipher("abcdefg"))
print(atbash_cipher("hello"))
print(atbash_cipher("world"))
zyxwvut
svool
dliow

How It Works

The ASCII-based method works as follows:

  • ord('a') = 97 and ord('z') = 122

  • N = 97 + 122 = 219

  • For 'a': chr(219 - 97) = chr(122) = 'z'

  • For 'z': chr(219 - 122) = chr(97) = 'a'

Comparison

Method Readability Performance Best For
ASCII Calculation Medium Good Understanding the math
String Translation High Excellent Production code

Conclusion

The Atbash cipher is implemented by mapping each letter to its reverse position in the alphabet. Use ASCII arithmetic for educational purposes or str.maketrans() for cleaner, more efficient code.

Updated on: 2026-03-25T10:12:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements