Python int(): String to Integer Conversion & Multi-Base Parsing

The int([x, base=10]) built-in function constructs an integer object from a number or string, supporting custom numeric radixes from base 2 to 36.

Truncation & Arbitrary Precision: When passed a floating-point number, int() truncates toward zero by discarding the fractional part. Python integers possess arbitrary precision, growing as large as available system memory allows. Custom objects can define integer conversion by implementing __int__() or __index__(). To parse floats or convert to booleans, see float() and bool().

1. Syntax & Formal Parameter Specifications 🔝

The int() constructor provides two calling signatures:

# Formal syntax of built-in int()
# Form 1: Numeric conversion or zero-arg constructor
val = int([x])

# Form 2: String conversion with explicit base (2 to 36)
parsed_val = int(string_value, base=10)
Parameter Type Accepted Behavioral Details
x int, float, str, bytes The value to convert. If omitted, returns 0. Strings can include underscores as visual separators (e.g. 1_000).
base int (2 to 36, or 0) Radix for string parsing. Defaults to 10. If specified, x must be a string or byte object.
Return Value int An integer object with arbitrary precision.

2. Basic Usage: Truncation & String Parsing 🔝

When converting floating-point numbers, int() truncates strictly toward zero:

# 1. Zero-argument and float truncation
print("int():     ", int())       # 0
print("int('45'): ", int('45'))   # 45

# Floats are truncated toward zero (fractional part discarded)
print("int(4.1):  ", int(4.1))    # 4
print("int(4.99): ", int(4.99))   # 4
print("int(-4.99):", int(-4.99))  # -4 (truncation toward zero, NOT floor!)

# 2. String with surrounding whitespace and underscores
print("int('  100  '):   ", int('  100  '))    # 100
print("int('1_000_000'): ", int('1_000_000'))  # 1000000

Output:

int():      0
int('45'):  45
int(4.1):   4
int(4.99):  4
int(-4.99): -4
int('  100  '):    100
int('1_000_000'):  1000000
Truncation vs Floor: int(-4.99) returns -4 (truncating toward 0), whereas floor division -4.99 // 1 returns -5.0 (rounding toward negative infinity).

3. Multi-Base Parsing: Binary, Octal, Hex & Base-36 🔝

With an explicit base argument, int() parses strings in that radix (up to base 36):

# Parsing strings across different numeric radixes (base 2 to 36)
# Base 2 (Binary)
print("Base 2  '1011':", int('1011', 2))   # 11

# Base 8 (Octal)
print("Base 8  '71':  ", int('71', 8))     # 57

# Base 16 (Hexadecimal)
print("Base 16 'cd':  ", int('cd', 16))    # 205
print("Base 16 '0xca':", int('0xca', 16))  # 202 (optional prefix tolerated)

# Base 36 (Alphanumeric digits 0-9 and a-z)
print("Base 36 'z':   ", int('z', 36))     # 35
print("Base 36 'python':", int('python', 36)) # 1573355473

Output:

Base 2  '1011': 11
Base 8  '71':   57
Base 16 'cd':   205
Base 16 '0xca': 202
Base 36 'z':    35
Base 36 'python': 1573355473

4. Custom Class Integration with __int__() and __index__() 🔝

Classes define integer conversion by implementing __int__() or __index__():

# Custom classes implementing __index__() or __int__()
class MoneyAmount:
    def __init__(self, dollars: int, cents: int):
        self.dollars = dollars
        self.cents = cents

    def __int__(self) -> int:
        # Returns total cents as integer
        return self.dollars * 100 + self.cents

wallet = MoneyAmount(12, 50)
print("Wallet object:       ", wallet)
print("int(wallet) in cents:", int(wallet))

Output:

Wallet object:        <__main__.MoneyAmount object at ...>
int(wallet) in cents: 1250

5. Unbounded Arbitrary Precision Integers 🔝

Python 3 integers have unbounded arbitrary precision, growing as needed in RAM:

# Arbitrary precision in Python 3 integers
# In Python 3, integers have unbounded size, limited only by available RAM
huge_power = int(2) ** 256
print("2^256 bit length:  ", huge_power.bit_length())
print("2^256 decimal string length:", len(str(huge_power)))

Output:

2^256 bit length:   257
2^256 decimal string length: 78

6. Production Recipes & Practical Applications 🔝

Below are real-world recipes utilizing int() for safe parsing and base-36 URL slug conversions:

# Recipe A: Safe integer parser with fallback
def safe_int(raw: str, default: int = 0) -> int:
    try:
        return int(float(str(raw).strip()))
    except (ValueError, TypeError):
        return default

print("safe_int('  45.8  '):", safe_int("  45.8  "))
print("safe_int(None):      ", safe_int(None))

# Recipe B: Base-36 slug decoding
print("Decode 'qglj' base 36:", int('qglj', 36))

Output:

safe_int('  45.8  '): 45
safe_int(None):       0
Decode 'qglj' base 36: 1234567

7. Common Pitfalls & Developer Traps 🔝

Frequent Traps with int()
  • Direct String Float Conversion: Calling int("4.5") raises a ValueError. Convert to float first: int(float("4.5")).
  • Base Argument with Non-String: Supplying a base to a non-string (e.g. int(123, 16)) raises a TypeError. Pass a string instead: int("123", 16).
  • None Type Conversions: int(None) raises TypeError. Use int(val or 0) to guard against None.
# Pitfall 1: int() does NOT directly parse decimal string floats
try:
    int("4.5")  # ValueError!
except ValueError as err:
    print("ValueError caught:", err)

# Solution for string floats: convert to float first, then int
print("int(float('4.5')):", int(float("4.5")))

# Pitfall 2: Explicit base cannot be used with non-string numbers
try:
    int(123, 16)  # TypeError!
except TypeError as err:
    print("TypeError caught: ", err)

Output:

ValueError caught: invalid literal for int() with base 10: '4.5'
int(float('4.5')): 4
TypeError caught:  int() can't convert non-string with explicit base

8. Interactive Notebook & Practice Exercises 🔝

Practice integer conversions, base-36 parsing, and safe string parsers in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells, benchmark base conversion performance, implement slug encoders, and run self-validating assertions.

View on GitHub Run in Google Colab

Self-Verifying Assertion Suite

Run these unit checks directly in Python or your local environment to verify int() mechanics:

def test_int_mechanics():
    # 1. Basic conversions
    assert int() == 0
    assert int(4.9) == 4
    assert int(-4.9) == -4
    assert int(" 42 ") == 42
    
    # 2. Base conversions
    assert int("1011", 2) == 11
    assert int("71", 8) == 57
    assert int("cd", 16) == 205
    assert int("z", 36) == 35
    
    # 3. Custom __int__
    class Item:
        def __int__(self): return 99
    assert int(Item()) == 99
    
    print("All int() unit assertions passed! 100% verified.")

test_int_mechanics()

Output:

All int() unit assertions passed! 100% verified.
float()

Converts numbers or strings into floating-point numbers.

bin()

Converts an integer to a binary string prefixed with 0b.

oct()

Converts an integer to an octal string prefixed with 0o.

hex()

Converts an integer to a hexadecimal string prefixed with 0x.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer