Click to See Complete Forum and Search --> : Rot13 in Python


NecroLin
05-21-2005, 06:10 AM
I've only just begun getting a taste of Python & have a quick question. Is there any easy way to change a character (Rot13 style, so the letter 'a' becomes the 13th char of the alphabet & the 13th char becomes the 'a', etc) in Python?

Many other programming languages let you just add/subtract 13 to a char to change it, but Python allways concatenates & doesn't seem to allow any operations to be done on strings (yes I know that they're immutable).

The solution is probably SO EASY.... I just can't figure it out....:(

Any ideas?

(Supa thanks in advanced)

bwkaz
05-21-2005, 09:12 AM
Starting with an ASCII string named srcstring, I think this for loop is valid:

for char in srcstring:
val = ord(char)
if val > 96 and val < 123:
# lowercase letter
val = ((val - 83) mod 26) + 96
elif val > 64 and val < 91:
# uppercase letter
val = ((val - 51) mod 26) + 64
deststring += chr(val) ROT13 is not supposed to change non-letter characters, IIRC.

If you're starting with a Unicode string instead of an ASCII string, then change "chr" to "unichr" in the last line. Actually, unichr() might work anyway... I'm not sure on that though.

NecroLin
05-21-2005, 09:34 AM
Thanks for the reply bwkaz. I'll give it a try. Looks like I need to learn a lot more Python!!! (Just started this week).

I get the gist of what the code is doing, but what do 'mod' & 'chr' do? I've never used them yet.:rolleyes:

Thanks again.

AdamZ
05-21-2005, 01:18 PM
Look at the codecs (http://docs.python.org/lib/module-codecs.html) module. It's got a rot13 encoding built in, so all you should have to do (if I'm understanding the documentation correctly) is call codecs.getencoder("rot_13") to get a function, and then call it with your input string (remember that encoding and decoding in rot13 are the same operation, so you don't need to get a decoder function as well).

NecroLin
05-22-2005, 07:15 AM
Awsome. I'll look into those codecs AdamZ.

bwkaz
05-22-2005, 03:23 PM
Oooh, that is better. I'll have to remember that codecs module. ;)

Originally posted by NecroLin
what do 'mod' & 'chr' do? 'mod' does a modulo operation.

a mod b is the remainder when a is divided by b. No number's modulo can ever be >= b.

Modulo is also an easy way of making values "wrap around" a range of values. Instead of checking whether the result is bigger than the range and subtracting from it, you just use mod, and mod does it for you.

'chr' takes a number and constructs an ASCII character from it. It returns a string whose only character is the character that corresponds to the numeric value you gave it in the ASCII character set.

'ord' does the opposite.

chr(ord(one-char-string)) returns one-char-string. chr(65) is "A" (uppercase A, in ASCII, is represented by the numeric value 65).

NecroLin
05-22-2005, 07:27 PM
Super thanks for your help.

Should have lots of time to play with both ways of doing rot13 today. :D