How to Convert an Octal String to an Integer in Python?

In Python, you can use the int() method (with a base 8 as the second argument) to convert an octal string to its integer equivalent, for example, like so:

num = int('30071', 8)

print(num) #=> 12345

This also works with octal strings that have the "0o" (or "0O") octal radix prefix:

# Python 2.6+
num = int('0o30071', 8)

print(num) #=> 12345
# Python 2.6+
num = int('0O30071', 8)

print(num) #=> 12345

Specifying an invalid octal number would raise the following error:

// ValueError: invalid literal for int() with base 8: '0x30071'
int('0x30071', 8)

If the octal string has 0o (or 0O) radix prefix, then you may also specify 0 as the second argument (i.e. the base) to the int() method, which would make it infer the value:

# Python 2.6+
num = int('0o30071', 0)

print(num) #=> 12345

This could be useful, for example, if a variable with a number can be of different types (such as binary, octal, hexadecimal, etc.).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.