# [Tutor] Doing this in reverse?

Kent Johnson kent37 at tds.net
Sun Sep 14 13:48:02 CEST 2008

```On Sun, Sep 14, 2008 at 3:08 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> The built-in int() function does what you need - give it a string
> representation of a number in any base 2-36; pass the base as the second
> argument.  The return is an integer - a pure, Platonic integer - which you
> can then print in any base you choose.
> If you omit the second argument (as you usually do), the base is assumed to
> be 10.
> The documentation says that if you pass 0 as the second argument, Python
> will try to guess the base, but it didn't work when I tried it.

The docs say, "If radix is zero, the proper radix is guessed based on
the contents of string; the interpretation is the same as for integer
literals."

'guessed' is not really a very good choice of words; 'determined'
might be better. The last part of the sentence is the clue.

With one argument, int() expects just the string representation of an
int; any characters that are not digits are an error. For example:

In [7]: int('0xaa')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

ValueError: invalid literal for int() with base 10: '0xaa'

If you pass 0 as the second argument, int() interprets the usual
prefix for integer literals, and the above works:

In [4]: int('0xaa', 0)
Out[4]: 170

Also notice the difference here:
In [5]: int('011')
Out[5]: 11

In [6]: int('011', 0)
Out[6]: 9

In the first case, the leading 0 has no special meaning and the result
is 11. In the second case, the leading 0 is interpreted to mean
'octal' and the result is different.

Kent
```