What does second parameter in python3 int(param1, param2) mean when it is set to 0?

1.9k views Asked by At

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.

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

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, with 0o16 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 to 0:

>>> int('16')       # default base 10
16
>>> int('16', 0)    # no prefix, still base 10
16
>>> int('0x16', 0)  # 0x prefix makes it base 16, hexadecimal
22
>>> int('0o16', 0)  # 0o prefix is interpreted as base 8, octal
14
>>> int('0b101', 0) # 0b prefix means base 2, binary
5

int() with any base other than 0 takes zero-padded strings:

>>> int('016')
16

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:

>>> int('016', 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: '016'

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.