Home
Python
ROT13 Method
Updated Apr 15, 2025
Dot Net Perls
ROT13. The ROT13 algorithm obscures text—it does not encrypt the text. The algorithm shifts each character back, or forward, 13 places.
Cipher code. ROT13 is a cipher algorithm that can deter unwanted examination. We implement it with Python—several Python language features are needed.
Example. We define a method called rot13(). We use the for-loop to iterate over the string characters. And then we call the ord() built-in function.
for
ord
So We compare each integer representation against lowercase and uppercase letters. We subtract or add 13 to shift characters.
And We append to the result string the character representation of the integer. We call chr() to do this.
def rot13(s): result = "" # Loop over characters. for v in s: # Convert to number with ord. c = ord(v) # Shift number back or forward. if c >= ord('a') and c <= ord('z'): if c > ord('m'): c -= 13 else: c += 13 elif c >= ord('A') and c <= ord('Z'): if c > ord('M'): c -= 13 else: c += 13 # Append to result. result += chr(c) # Return transformation. return result # Test method. print(rot13("gandalf")) print(rot13(rot13("gandalf")))
tnaqnys gandalf
Notes, tests. We test to make sure the rot13() method is correct. When we call rot13() on the result of rot13(), we again have our original string value.
Thus The rot13() algorithm round-trips its data correctly—the original data is not lost. This is correct.
Discussion. The ROT13 algorithm is an important one to implement. It is a handy way to add obscurity—text that is not easily readable. This is useful in certain situations.
Also The algorithm helps teach us how to treat characters as numbers. In Python we do this with ord() and chr(), two built-in functions.
Detail A faster implementation is possible using the translate method. We benchmark and implement one.
String translate
The ROT13 algorithm is well-known and can help us learn how to use core Python features. Ciphers, such as ROT13, are occasionally useful.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 15, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen