-
Rot13 in Python
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)
-
Starting with an ASCII string named srcstring, I think this for loop is valid:
Code:
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.
-
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.
Thanks again.
-
Look at the codecs 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).
Adam
Dell Inspiron 600m
P-M 1.6 GHz | 512MB RAM | IPW2100 Wireless | CDRW/DVD-ROM | 40GB HDD
-
Awsome. I'll look into those codecs AdamZ.
-
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).
-
Super thanks for your help.
Should have lots of time to play with both ways of doing rot13 today.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|