int('0x0001')

Joshua Macy amused at webamused.com
Thu Mar 16 10:00:39 EST 2000


Michal Bozon wrote:
> 
> Why int() cannot handle string of hexadecimal representation of integer?
> I mean e.g.  int('0xA') -> 10.
> 
> I have to use eval('0xA')
> 
> regards,
> Michal Bozon
> bozon at natur.cuni.cz
> http://www.natur.cuni.cz/~bozon

  Because int(X) takes a number or a string X and converts it to an
integer, and '0xA' is neither?  If you want to convert a string
representation of a hexadecimal number to an integer, you want the
string.atoi function, which lets you specify a base.

Python 1.5.1 (#1, Apr  3 1999, 18:41:12)  [GCC egcs-2.91.60 19981201 (e
on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> int('0xA')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 0xA
>>> import string
>>> string.atoi('0xA', 16)
10

Generally, a quick look at the online documents and a moment of playing
around with the interpreter makes it easy to answer questions like
this.  Not that you shouldn't ask for help on the newsgroup, but you'll
be amazed at how much more productive you'll become once you get used to
the idea of trying things out interactively; it's one of Python's great
strengths.


Joshua



More information about the Python-list mailing list