int Parses Numbers In An Explicit Base

int(text, base) reads digits in the given radix, base 0 trusts 0b/0o/0x prefixes, and format or bin/oct/hex write integers back out in any base.

PythonConfig Management

Code

pythonsnippet
24 lines
# int(text, base) 按显式进制解析;base=0 时由前缀决定进制
print("binary  :", int("0b1011", 2), int("0b1011", 0))
print("octal   :", int("0o17", 8), int("0o17", 0))
print("hex     :", int("0xff", 16), int("0xff", 0))
print("decimal :", int("42", 0))

# 不带前缀时必须给出进制,否则按十进制解析
print("no prefix base 10:", int("1011"))
print("no prefix base 2 :", int("1011", 2))

# 下划线隔位是合法的:长数字的读写形式
print("underscores      :", int("1_000_000", 10))

# 反向:format 与 bin/hex 把整数写回各进制文本
value = 493
print("formatted:", format(value, "b"), format(value, "o"), format(value, "x"), format(value, "#x"))
print("builtins :", bin(value), oct(value), hex(value))

# 非法字符按给定进制抛出 ValueError,错误信息指出位置
for text in ["12x", "0b2"]:
    try:
        int(text, 0)
    except ValueError as exc:
        print("invalid:", repr(text), "->", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

binary  : 11 11
octal   : 15 15
hex     : 255 255
decimal : 42
no prefix base 10: 1011
no prefix base 2 : 11
underscores      : 1000000
formatted: 111101101 755 1ed 0x1ed
builtins : 0b111101101 0o755 0x1ed
invalid: '12x' -> invalid literal for int() with base 0: '12x'
invalid: '0b2' -> invalid literal for int() with base 0: '0b2'

Inside the snippet

One loop does the cycling here: for text in ["12x", "0b2"].

Module-level bindings hold the data — value — with no function scope in between.

Using it

The run emits 10 labeled sections — binary :, octal :, hex :, decimal :, no prefix base 10:, no prefix base 2 :, underscores :, formatted:, builtins :, invalid: — one per step.

Key statements

except ValueError as exc:
    print("invalid:", repr(text), "->", exc)

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `value`.