[Tutor] sprintf-like functionality in Python

Alexandre Ratti alex at gabuzomeu.net
Mon Aug 25 19:48:25 EDT 2003


Hi Vicki


Vicki Stanfield wrote:
> I am looking for something like sprintf functionality in Python. I have
> seen several things on google groups that seem to indicate that sprintf
> itself exists in Python but I haven't really found an explanation of it.
> What I am trying to do is take data with comes into my program as hex and
> convert it to ASCII. For instance, I get:
> 
> 0x30
> 0x35
> 
> This represents the length of 5 (05), and I need to convert it to the
> integer 5. The problem is that the first digit might be significant as in
> (0x32 0x35) which translates to 25. I am not sure how to put the two
> together in Python. In C, I'd use sprintf. In short, I start with 0x32
> 0x35 and need to translate it to the integer 25. 

If only the last digit is significant, you might try this:

 >>> ("%x" % 0x35)[-1]
'5'
 >>> ("%x" % 0x32)[-1]
'2'
 >>> l = [0x32, 0x35]
 >>> int("".join([("%x" % x)[-1] for x in l]))
25

It's probably not the most elegant solution, but it seems to work.


Cheers.

Alexandre






More information about the Tutor mailing list