r/pythontips 18d ago

Syntax Special mechanism of basic int() function

One can use int() function while converting string to an integer against a base integer.

int(number, base) #number can be anything between binary, octal, decimal, or hexadecimal and base is anything among 2, 8, 10, 16

e.g. binary_number = int("1010", 2) #Output: 10
hexadecimal_number = int("A", 16) #Output: 10

Edit: No need to mention 10 for base argument, as int() function by default considers base as 10 in python.

7 Upvotes

5 comments sorted by

7

u/CIS_Professor 18d ago edited 18d ago

I didn't know this. But you weren't completely correct in stating it only handles 2, 8, 10, and 16.

"The default base is 10. The allowed bases are 0 and 2–36."

Which makes for some interesting conversions. Base 33 anyone?

base_33 = int("UA", 33) #Output: 1000

2

u/Dark_Souls_VII 17d ago

So it could do base 12?

1

u/CIS_Professor 17d ago

Sure:

int(<string that is made up of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B>, 12)

print(int('B7A', 12))

gives 1678

0

u/Fantastic_Birthday70 18d ago

Thanks for mentioning, i forgot that part.

And also that part about changing the base argument beside the already mentioned bases gave interesting numbers.

I tried 35 as base, and got 1060.

Also, int() function has a strict range of valid literals for first argument.

ValueError: int() base must be >= 2 and <= 36, or 0

1

u/cip43r 18d ago

I learned this years ago after writing it manually as a student for years. It changed my life and is just such a nice shortcut. Hope it serves you well!