Need to add to ord and convert to chr
David Goodger
dgoodger at bigfoot.com
Sun Nov 5 20:56:59 EST 2000
on 2000-11-05 15:42, mchitti at my-deja.com (mchitti at my-deja.com) wrote:
> Trying to teach myself python, would appreciate any help.
This is the place!
> I have a long string of letters (a caesar cipher) which I chop up,
> convert to ord values and stick into a list. I need to be able to add
> an arbitrary interger to the ord values and then convert back to char.
> This should allow me to brute force the cipher if my logic is good.
The other two replies so far have valid points, but the code has a bug.
Caesar ciphers need to wrap around when you add the offset, so that 'z' + 1
== 'a'.
By the way, your example message doesn't seem to be a valid Caesar cipher.
Should it be?
The code below will do what you want, and works in 1.5.2.
--
David Goodger dgoodger at bigfoot.com Open-source projects:
- The Go Tools Project: http://gotools.sourceforge.net
(more to come!)
---------- cut here ---------- cut here ---------- cut here ----------
#!/usr/bin/env python
import string
def caesar(message, offset):
result = []
orda = ord('a')
ordz = ord('z')
for c in string.lower(message):
ordchar = ord(c)
if orda <= ordchar < ordz:
result.append(chr((ordchar - orda + offset) % 26 + orda))
else: # if not a letter, don't convert
result.append(c)
return string.join(result, '')
message = 'weet bksa myjx oekh fojxed ijktyui!'
for offset in range(26): # test all offsets
print '\noffset by:', offset
result = caesar(message, offset)
print result
More information about the Python-list
mailing list