[Tutor] Iterate over letters in a word

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Mar 14 19:40:14 CET 2006


> "Hello Tutors!" could be split into:
>
> "Hell" "o Tut" "ors!"
>
> and xor'd with "beer"
>
> I think I understand how xor works (thanks to an earlier post) but I'm
> not sure how to iterate over each letter in a string.  What is the
> recommended way to do this?

The xor bitwise operator works with numbers --- not directly with strings
--- so one of your tasks will probably be to take a chunk like:

    "beer"

and turn it into some numeric bit pattern.


It turns out that this isn't too bad if we abuse the 'struct' module:

    http://www.python.org/doc/lib/module-struct.html


The idea is to unpack four single characters as a single 4-byte integer.
For example:

######
>>> struct.unpack('i', 'food')
(1685024614,)
######


This kind of transformation is reversable:

######
>>> struct.pack('i', 1685024614)
'food'
######


Does this make sense?



More information about the Tutor mailing list