Python int() function: Convert Strings, Floats & Booleans to Integers

Converting String to Integer in Python Using int()

String-to-integer conversion is one of the most frequently used operations in Python. Whether you are parsing user input, reading data from files, or cleaning datasets, converting strings into integers is essential for performing numeric computations accurately.
The built-in int() function handles this seamlessly, allowing you to convert valid numeric strings into integers. Let’s explore all the key concepts, examples, and edge cases.

What is String-to-Integer Conversion?

In Python, string-to-integer conversion refers to converting a string that represents a whole number into an integer type using the int() function.

Syntax of String-to-Integer Conversion


int(string_value)

Parameter Description:

Parameter Description
string_value A string containing a valid integer (e.g., “123”)

Valid String Examples

Example 1: Basic Positive Number


num = int("123") print(num) # Output: 123
Explanation:

Converts the string “123” into the integer 123.

Example 2: Zero


num = int("0") print(num) # Output: 0
Explanation:

Works even when the string contains “0”.

Example 3: Leading Zeros


num = int("007") print(num) # Output: 7
Explanation:

Python ignores leading zeros in numeric strings.

Example 4: Negative Numbers


num = int("-456") print(num) # Output: -456
Explanation:

Handles negative integers correctly when prefixed with -.

Example 5: Positive Sign


num = int("+789") print(num) # Output: 789
Explanation:

Strings with an explicit + sign are also valid.

Invalid String Examples and Errors


#1. String with Decimal Point

# num = int("12.34") # ValueError

Explanation: Strings containing decimals cannot be converted to integers directly.

#2. Non-Numeric Characters

# num = int("abc") # ValueError

Explanation: Only strings containing valid digits (and an optional sign) are allowed.

#3. Mixed Characters

# num = int("123abc") # ValueError

Explanation: A string must contain only numeric characters to be converted.

Pro Tip: Before converting strings, you can validate numeric strings using .isdigit() to avoid runtime errors:


#1. String with Decimal Point

s = "1234" if s.isdigit(): print(int(s)) # Output: 1234

Summary Table

String Value int() Output Valid?
“123” 123
“007” 7
“-89” -89
“12.5” Error
“abc” Error
“123abc” Error

Binary String to Integer Conversion in Python

  • In many real-world applications—like computer architecture, network protocols, and embedded systems—binary numbers are frequently used. Python makes it easy to convert a binary string into an integer using the built-in int() function.
  • Here e are going to explore every detail of binary string to integer conversion using simple explanations and multiple examples.

What is a Binary String?

A binary string is a string that represents a number in base-2 numeral system, using only the digits 0 and 1.

For example:

  • “1010” (represents 10 in decimal)
  • “111” (represents 7 in decimal)

Why Convert Binary String to Integer?

Binary data is often transmitted or stored as text. To perform mathematical operations or comparisons, it must first be converted into an integer.

Syntax of Convert Binary String to Integer


int(string, base=2)

Parameter Description:

Parameter Description
string A string containing only 0 and 1
base Set to 2 to specify that the string is binary

Valid Examples: Convert Binary String to Integer in Python

Example 1: Simple Binary


print(int("1010", 2)) # Output: 10 #"1010" is 1×8 + 0×4 + 1×2 + 0×1 = 10

Example 2: Single Digit


print(int("1", 2)) # Output: 1 print(int("0", 2)) # Output: 0

Example 3: With Leading Zeros


print(int("000101", 2)) # Output: 5 #Leading zeros are ignored.

Example 4: Larger Binary Number


print(int("11111111", 2)) # Output: 255 print(int("100000000", 2)) # Output: 256

Invalid Binary String Examples


#Example 1: Contains Characters Other Than 0 and 1

print(int("11111111", 2)) # Output: 255 print(int("100000000", 2)) # Output: 256

# Example 2: Prefix with 0b

# print(int("0b1010", 2)) # ValueError "0b" prefix is valid in Python integer literals, not in strings passed to int(). # Correct Way: print(int("1010", 2)) # Output: 10

Advanced Examples


# Example 1: Convert Binary String Stored in a Variable

binary_string = "1101" decimal_value = int(binary_string, 2) print(decimal_value) # Output: 13

# Example 2: Convert Multiple Binary Strings

binaries = ["1", "10", "100", "1000", "10000"] for b in binaries: print(f"{b} -> {int(b, 2)}") #Output: 1 -> 1 10 -> 2 100 -> 4 1000 -> 8 10000 -> 16

# Example 3: Binary String from Input

binary_input = "1110" if all(ch in "01" for ch in binary_input): print(int(binary_input, 2)) # Output: 14 else: print("Invalid binary string") #Validates string before conversion.

# Example 4: Using bin() and int() Together

decimal_number = 23 binary_string = bin(decimal_number)[2:] # '10111' print(binary_string) # Output: '10111' print(int(binary_string, 2)) # Output: 23
Binary String Decimal Output
“0” 0
“1” 1
“10” 2
“1010” 10
“11111111” 255
“100000” 32
Pro Tip: Use bin() to Go Back to Binary


print(bin(255)) # Output: '0b11111111' # Removes the need to manually convert integers back to binary strings.

Conclusion

Binary-to-integer conversion is a fundamental tool in Python when dealing with

  • Binary-encoded data
  • File permissions
  • Bitwise operations
  • Network packets

By using int(binary_string, 2), Python handles the conversion efficiently with excellent error-checking capabilities.h

Converting Octal String to Integer in Python

  • Octal numbers are base-8 numbers that use digits from 0 to 7. In various domains—like file permissions in Unix/Linux, digital electronics, and legacy systems—octal notation plays an important role. Python provides an easy way to convert octal strings to decimal integers using the built-in int() function.
  • Here we are going to explain how to convert an octal string to an integer in Python, covering all concepts and scenarios with clear examples.

What Is an Octal String?

An octal string is a string representation of a number in base-8 format. It uses only the digits:
0, 1, 2, 3, 4, 5, 6, 7

Why Convert an Octal String to Integer?

To perform mathematical operations, octal strings must be converted into integers.

Syntax: Using int() with Base 8


int(string, base=8)
Parameter Description
string The string containing octal digits
base Set to 8 to specify octal conversion

  • Unix file permissions (e.g., 0755)
  • Embedded systems
  • Low-level programming
  • Bitmask operations
  • Valid Examples: Convert Octal String to Integer in Python

    
    

    # Example 1: Basic Octal String

    print(int("10", 8)) # Output: 8 # "10" in octal is 8 in decimal (1×8 + 0×1)

    # Example 2: Convert File Permission String

    print(int("755", 8)) # Output: 493 #"755" octal maps to Unix file permission -rwxr-xr-x in decimal.

    # Example 3: Octal String with Leading Zeros

    print(int("0007", 8)) # Output: 7 #Leading zeros are ignored.

    # Example 4: Maximum Octal Digit

    print(int("777", 8)) # Output: 511 #All digits are 7, the highest allowed in base-8.

    # Example 5: Octal String Stored in a Variable

    octal_string = "17" decimal = int(octal_string, 8) print(decimal) # Output: 15

    Invalid Examples: Convert Octal String to Integer in Python

    
    

    # Example 1: Contains Digits 8 or 9

    # print(int("89", 8)) # ValueError #Digits 8 and 9 are not allowed in base-8.
    
    

    #Example 2: Contains Letters

    # print(int("7g", 8)) # ValueError #Octal strings must contain digits only (0-7).
    
    

    #Example 3: Python Octal Literal Prefix (0o)

    # print(int("0o10", 8)) # ValueError The 0o prefix is used in Python integer literals, not inside strings. # Correct way: print(int("10", 8)) # Output: 8

    Real-World Scenarios: Convert Octal String to Integer in Python

    
    

    #Example 9: File Permission from User Input

    permission_input = "644" if all(d in "01234567" for d in permission_input): print(int(permission_input, 8)) # Output: 420
    
    

    #Example 10: Loop through Octal Strings

    octals = ["10", "20", "30", "40", "50"] for o in octals: print(f"{o} in octal = {int(o, 8)} in decimal") #Output: 10 in octal = 8 in decimal 20 in octal = 16 in decimal 30 in octal = 24 in decimal 40 in octal = 32 in decimal 50 in octal = 40 in decimal
    
    

    #Example 11: Validate Octal Before Converting

    def is_valid_octal(s): return all(c in "01234567" for c in s) octal_str = "345" if is_valid_octal(octal_str): print(int(octal_str, 8)) # Output: 229

    Back and Forth Conversion

    
    

    1. Convert an integer to an octal string using oct():

    print(oct(64)) # Output: '0o100'

    2. To remove the prefix:

    print(oct(64)[2:]) # Output: '100'
    Octal String Decimal Value
    “0” 0
    “7” 7
    “10” 8
    “17” 15
    “377” 255
    “755” 493

    Conclusion

    Python provides a simple, reliable way to convert octal strings into integers using int(string, 8). This is highly useful in system-level tasks and bitwise operations.

    Key Takeaways:

    • Use only digits 0-7
    • Always pass base=8 in int()
    • Handle invalid characters with validation

    Converting Hexadecimal String to Integer in Python

    • Hexadecimal (or hex) numbers are base-16 representations of values using digits:
    • 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A–F (or a–f)
    • These are widely used in computing, digital electronics, and color codes. Python offers a very simple and powerful way to convert hexadecimal strings into decimal (base-10) integers.

    Why Hexadecimal?

    • Compact representation of binary values
    • Common in memory addresses, MAC addresses, and color values
    • Used heavily in low-level programming, cryptography, and network protocols

    Why Convert an Hex String to Integer?

    Octal numbers are common in:

    • To process data from low-level systems like memory addresses or registers
    • To work with color codes, file formats, or network protocols
    • To convert user or file input into a usable numeric form
    • To bridge human-readable hex values with program logic

    How to Convert Hex String to Integer?

    To perform mathematical operations, Hex String must be converted into integers. Python’s built-in int() function can be used for this.

    Syntax: Using int() with Base 16

    
    

    int(hex_string, 16)
    Parameter Description
    hex_string A string containing a hex number
    16 The base (16) indicating hexadecimal

    Valid Examples: Convert Hexadecimal String to Integer in Python

    
    

    Example 1: Simple Hex String

    print(int("1A", 16)) # Output: 26 #"1A" hex = (1 × 16) + (10 × 1) = 26

    #Example 2: Lowercase Letters

    print(int("ff", 16)) # Output: 255

    #Example 3: Uppercase Letters

    print(int("FF", 16)) # Output: 255

    #Example 4: Leading Zeros

    print(int("000f", 16)) # Output: 15

    #Example 5: Hex Stored in Variable

    hex_color = "a3" decimal = int(hex_color, 16) print(decimal) # Output: 163

    Invalid Examples: Convert Hexadecimal String to Integer in Python

    
    

    #Example 1: Contains Invalid Character

    # print(int("1G", 16)) # ValueError: invalid literal #Valid hex digits are only: 0-9, A-F, a-f
    
    

    #Example 7: Using "0x" Prefix in String

    # print(int("0x1F", 16)) # ValueError: invalid literal
    #Correct way (strip “0x” if it exists): print(int(“1F”, 16)) # Output: 31

    Real-World Scenarios: Convert Hexadecimal String to Integer in Python

    
    

    #Example 8: Convert a List of Hex Strings

    hex_values = ["1F", "2A", "3B"] for val in hex_values: print(f"{val} -> {int(val, 16)}") #Output: 1F -> 31 2A -> 42 3B -> 59
    
    

    #Example 9: Hexadecimal Color Code to Integer RGB

    color_hex = "FFA500" # Orange r = int(color_hex[0:2], 16) g = int(color_hex[2:4], 16) b = int(color_hex[4:6], 16) print(f"RGB = ({r}, {g}, {b})") # Output: RGB = (255, 165, 0)
    
    

    #Example 10: Validating Hex String

    def is_valid_hex(s): try: int(s, 16) return True except ValueError: return False print(is_valid_hex("1A")) # True print(is_valid_hex("G9")) # False

    Back and Forth Conversion

    
    

    1. Convert Integer to Hex String:

    print(hex(255)) # Output: '0xff'

    2. Remove "0x" Prefix:

    print(hex(255)[2:]) # Output: 'ff'

    Tips

    • Acceptable characters: 0–9, a–f, A–F
    • Do not include the “0x” prefix inside strings when using int()
    • Use hex() to convert back from decimal to hexadecimal

    Summary Table: Convert Hexadecimal String to Integer in Python

    Hex String Decimal Value
    “0” 0
    “1A” 26
    “FF” 255
    “100” 256
    “ABC” 2748
    “dead” 57005

    Conclusion: Convert Hexadecimal String to Integer in Python

    Hexadecimal string to integer conversion is a common task in many programming domains, especially system-level and hardware-level applications. With Python’s int() function and base=16, this becomes both clean and efficient.

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    Scroll to Top