Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Rainyan
Last active May 5, 2023 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rainyan/a9e3582466ead30c83a586bfe8db2763 to your computer and use it in GitHub Desktop.
Save Rainyan/a9e3582466ead30c83a586bfe8db2763 to your computer and use it in GitHub Desktop.
ROT-n cipher in Python 3, defaulting as ROT-13
from string import ascii_lowercase, ascii_uppercase
# Note that this already exists in Python as codecs.encode("text", "rot13")
# so you'd probably wanna use that instead of this implementation,
# unless you need a rotation of n places with n != 13.
def rot(text, rotation=13):
"""ROT-n cipher.
Decode by running the output through the function again
(assuming the rotation is exactly half of the used character set)."""
result = ""
for char in text:
if char.islower():
charset = ascii_lowercase
else:
charset = ascii_uppercase
pos = charset.find(char)
if pos == -1:
result += char # Not in charset? Append as-is.
continue
pos = (pos + rotation) % len(charset)
result += charset[pos]
return result
assert rot("foobar") == "sbbone"
assert rot("sbbone") == "foobar"
assert rot(rot("foobar")) == "foobar"
assert rot("Abc!") == "Nop!"
assert rot("Nop!") == "Abc!"
assert rot(rot("Abc!")) == "Abc!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment