How do I convert characters into integers?

Adam DePrince adam at cognitcorp.com
Wed Dec 15 23:59:13 EST 2004


On Tue, 2004-12-14 at 18:18, Paul Rubin wrote:
> Markus Zeindl <MarkusZeindl at web.de> writes:
> 
> > Now I get every character with a loop:
> > <code>
> > buffer = ""
> > for i in range(len(message)):
> >    ch = message[i-1:i]
> 
> You mean 
>   ch = message[i]
> what you have does the wrong thing when i = 0.
> 
> > Here is the problem. I got a string with one character and I
> > want his ascii representain, for "a" -> 97
> > but I want to calculate like iCh = iCh+3 or something else.
> 
> iCh = ord(ch)
> 
> > The next step is how I convert it back to an char and append it
> > to the buffer, but that' no problem.
> 
> ch = chr(iCh)


for i in range( len( message )):
	ch = message[ i ] # don't use message[i-1:i], yech!

Strings are also sequences in python.   You might find this weird, but
...

"anystring"[0] == "anysring"[0][0][0][0][0]
is always true.  Taking an element returns the character as a string of
length 1.

Think in terms of maping here.  Don't say ...
for ... 

Think ... 

message = map( ord, message ) 

or 

message = [chr( (ord( x ) + 3 )%256) for x in message]





Adam DePrince 





More information about the Python-list mailing list