int() should be extended?
Erik Max Francis
max at alcyone.com
Mon Oct 21 16:51:31 EDT 2002
Xiao-Qin Xia wrote:
> int() can convert some string into integer, except a string from
> hex():
> """
> >>> int("41")
> 41
> >>> int("041")
> 41
> >>> int("0x41")
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 0x41
> >>>
> >>> exec "c = 0x41"
> >>> c
> 65
> """
>
> since use exec is not so good a habit, is there any other way to convert
> "0x41" to 65 (0x41)?, or int() should be extened to do this job?
It already has, but I'm surprised nobody (except Frederik who posted the
doc string) has mentioned that a radix of 0 makes int autodetect the
radix, and so behaves just like you want to:
>>> int('23', 0)
23
>>> int('023', 0) # octal
19
>>> int('0x23', 0) # hex
35
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ I want a martini that could be declared a disaster area.
\__/ Capt. Benjamin "Hawkeye" Pierce
Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
A new, virtual planet, every day.
More information about the Python-list
mailing list