hex string to hex value

mensanator at aol.com mensanator at aol.com
Wed Nov 23 13:27:08 EST 2005


Fredrik Lundh wrote:
> mensanator at aol.com wrote:
>
> > Fredrik Lundh's solution works if the hex string starts with "0x"
>
> that's what "interpret [it] as a Python literal" meant.

I know from personal experience that the implications of that
sometimes go right over the head of a newbie. Did I do something
wrong by pointing out exactly what that means? Isn't it better to
have the OP understand the problem than simply solve it for him?

>
> > (which it will when the string is created with the hex function).
> >
> > >>> int(hex(m),0)
> > 66
> >
> > But it won't work without the "0x".
> >
> > >>> int('0x1A',0)
> > 26
> > >>> int('0x1A',16)
> > 26
> > >>> int('1A',16)
> > 26
> > >>> int('1A',0)
> >
> > Traceback (most recent call last):
> >   File "<pyshell#18>", line 1, in -toplevel-
> >     int('1A',0)
> > ValueError: invalid literal for int(): 1A
>
> as the error message says, 1A isn't a valid literal.

Yes, not all strings of valid hex characters are valid literals.
But surely you're not suggesting that the user simply give
up when faced with that situation?

> 
> </F>




More information about the Python-list mailing list