I'm reading documentation on the Python 3 int(...)
function and can't understand the following statement:
Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
Can someone explain what exactly it is saying? I can't figure it out.
Python integers can be expressed in different bases, by giving it a specific prefix. If you write
0x16
then the number is interpreted as hexadecimal, with0o16
you get an octal interpretation, etc. Writing integers in source code is known as literal syntax.You can pass such string value containing text using the same syntax to the
int()
function and have it figure out what base to use from such a prefix too, by setting the second argument to0
:int()
with any base other than0
takes zero-padded strings:but when you set the base to
0
such strings are no longer accepted, because the Python literal syntax for integers doesn't accept those either:In Python 2, you could use a leading zero like that, and that would be interpreted as an octal number, so base 8. That lead to confusing bugs, and the syntax was removed from Python 3, where only the
0o
prefix is now supported.