Need to add to ord and convert to chr

Alex Martelli aleaxit at yahoo.com
Sun Nov 5 17:42:56 EST 2000


<mchitti at my-deja.com> wrote in message news:8u4gn9$pe5$1 at nnrp1.deja.com...
    [snip]
> 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.

Ok.  The base idea (in Python 2) would be:

def caesar(msg,delta):
    return ''.join([chr(delta+ord(c)) for c in msg])

The ''.join part takes a list of characters and makes it back
into a string.  Its argument is a list-comprehension (the
Python-2 part of the answer).

The list-comprehension, for each character c in the msg,
turns it into a number (ord), adds delta (the 'arbitrary
integer' you want), turns the result back into a character
(chr), and makes a list of all of these characters.

The Python 1.5.2 equivalent...:

def caesar(msg, delta):
    result=[]
    for c in msg:
        result.append(chr(delta+ord(c)))
    return string.join(result)

Just a bit more verbose, but the semantics are virtually
identical.  The for-loop appending to an initially empty
string mimics the modern list-comprehension idea; the
string.join is equivalent to today's ''.join.


Alex






More information about the Python-list mailing list