[Python-ideas] int('0x3241fca1')
Andrew Barnert
abarnert at yahoo.com
Thu Feb 6 13:37:32 CET 2014
On Feb 6, 2014, at 4:28, spir <denis.spir at gmail.com> wrote:
> On 02/06/2014 11:24 AM, Ram Rachum wrote:
>> What do you think about letting the `int` constructor automatically
>> understand the number type without specifying base if given a prefix, so
>> int('0x3414fa') would immediately work without specifying a base of 16?
>
> Do you mean int(numeral), where numeral is a *variable* string, with a python base prefix? (Else, just type in the constant 0x3414fa ;-) If yes, then I find it a good idea. When int() is used to decode variable numerals, it could/should/would decode all correct python numeral notations.
>
> Note that int() also does not decode 'e' postfixes:
Of course it doesn't. A number with an e postfix is a float, not an int, so why should int parse it? You also can't use int to parse 123.45, or even 123.0, or a quoted string like "123", or "1+0j".
> Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
> [GCC 4.8.1] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> int(123e2)
> 12300
>>>> int("123e2")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 10: '123e2'
>
> But float() does:
>
>>>> float(-1.23e4)
> -12300.0
>>>> float("-1.23e4")
> -12300.0
>
> !
>
> After all, it's just a question of practical notational conventions (we don't use "hundred and twenty-three" or "CXXIII" or "v^^^^^v^^"). Python's own decoding builtins should be consistent with its own choice of notations.
In that case, int('-3') shouldn't work, because -3 is not a valid int literal in Python. (It's a unary expression with the '-' operator followed by the literal 3.)
More information about the Python-ideas
mailing list