[Tutor] sprintf-like functionality in Python

Jeff Shannon jeff at ccvcorp.com
Mon Aug 25 13:46:19 EDT 2003


Vicki Stanfield wrote:
>>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. Thanks.
>>
>>--vicki
> 
> 
> Okay I got it to work (not so elegently) using this:
> 
>             output=port.read()
>             length = chr(ord(output))
>             output=port.read()
>             newlength=length+chr(ord(output))
>             num=int(newlength)
>             print num
> 

I think that you're working too hard on this, perhaps as a result of 
being accustomed to working in C.  I suspect that what you're getting 
from port.read() is simply a string, and that if you just print the 
string, you'll get what you want.

Note that, if you're wanting a string representation of what you 
receive, there's really no need to convert it with int().

In fact, you're doing a lot of converting in this snippet that makes 
no difference at all.  'chr(ord(x))' returns x, as chr() and ord() are 
inverse functions, while 'print int(x)' is implicitly 'print 
str(int(x))', and str() and int() are inverse functions (presuming 
appropriate values of x) so this is equivalent to 'print x'.  In other 
words, what you're printing is exactly what you're reading from the 
port, despite a lot of handwaving that makes it *look* like you've 
transformed it several times.

Now, if you eliminate the redundancies, you'll have something like this:

output = port.read()
newlength = output + port.read()
print newlength

If, at this point, what's printed is a two-digit hex code (say, '32'), 
then we can convert that into an ASCII character like so:

print chr(int(newlength, 16))

but you should probably look carefully at what newlength is before you 
assume that you'll need to make this conversion.  What in C is a 
series of bytes (normally represented using hex), in Python is just an 
ordinary string, and that's exactly what you're getting from read(). 
I suspect (though I can't be sure) that Python is already doing all of 
the conversion that you need done, automatically.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list