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 |
# Example 1: Basic Octal String # Example 2: Convert File Permission String # Example 3: Octal String with Leading Zeros # Example 4: Maximum Octal Digit # Example 5: Octal String Stored in a Variable # Example 1: Contains Digits 8 or 9 #Example 2: Contains Letters #Example 3: Python Octal Literal Prefix (0o) #Example 9: File Permission from User Input #Example 10: Loop through Octal Strings #Example 11: Validate Octal Before Converting 1. Convert an integer to an octal string using oct(): 2. To remove the prefix: 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: Octal numbers are common in: To perform mathematical operations, Hex String must be converted into integers. Python’s built-in int() function can be used for this. Example 1: Simple Hex String #Example 2: Lowercase Letters #Example 3: Uppercase Letters #Example 4: Leading Zeros #Example 5: Hex Stored in Variable #Example 1: Contains Invalid Character #Example 7: Using "0x" Prefix in String #Example 8: Convert a List of Hex Strings #Example 9: Hexadecimal Color Code to Integer RGB #Example 10: Validating Hex String 1. Convert Integer to Hex String: 2. Remove "0x" Prefix: 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.Valid Examples: Convert Octal String to Integer in Python
Invalid Examples: Convert Octal String to Integer in Python
Real-World Scenarios: Convert Octal String to Integer in Python
Back and Forth Conversion
Octal String
Decimal Value
“0”
0
“7”
7
“10”
8
“17”
15
“377”
255
“755”
493
Conclusion
Converting Hexadecimal String to Integer in Python
Why Hexadecimal?
Why Convert an Hex String to Integer?
How to Convert Hex String to Integer?
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
Invalid Examples: Convert Hexadecimal String to Integer in Python
#Correct way (strip “0x” if it exists):
print(int(“1F”, 16)) # Output: 31
Real-World Scenarios: Convert Hexadecimal String to Integer in Python
Back and Forth Conversion
Tips
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