C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Python program that does rot13 transformation
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")))
Output
tnaqnys
gandalf
Thus: The rot13() algorithm round-trips its data correctly. The original data is not lost. This is correct.
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.
Translate: A faster implementation is possible using the translate method. We benchmark and implement one.
Translate