[Tutor] sprintf-like functionality in Python
Rick Pasotto
rick at niof.net
Mon Aug 25 16:01:23 EDT 2003
On Mon, Aug 25, 2003 at 01:35:57PM -0500, 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
>
> Anyway, it works...unless output is a letter which it can be since it is
> hex. I get an error:
>
> ValueError: invalid literal for int(): A
>
> In that case, what I want is the base10 representation of the hexadecimal
> letter. I thought that I could use
>
> chr(ord(output), 16)
>
> but that yields an error:
>
> TypeError: chr() takes exactly 1 argument (2 given)
>
> I am so close, but I can't quite get this figured out. Anyone?
>
> --vicki
I think you're doing too much.
c1 = 0x32
c2 = 0x35
So now c1 and c2 are the results of your port.read(), right?
c = chr(c1) + chr(c2)
This gives: c => '35'
Now all you need is int(c).
Drop the 'ord()' and what you have should work.
--
"Every election is a sort of advance auction of stolen goods."
--- H. L. Mencken
Rick Pasotto rick at niof.net http://www.niof.net
More information about the Tutor
mailing list