How to Convert String to Int in Python (Safe Casting & Bases)
Learn how to convert a string to an integer in Python using the int() function. Handle errors safely and convert numbers from binary, octal, or hex.
Explanation
Converting a string representation of a number into an actual integer is a frequent task in application development. This process, often referred to as casting, is essential when dealing with raw user input, reading configuration files, parsing arguments from command-line interfaces, or scraping data from the web. Since Python is a strongly typed language, you cannot perform mathematical operations on string representations of numbers without casting them first.
Python's built-in `int()` constructor is the primary tool for this conversion. In its simplest form, passing a numeric string (like `"42"`) to `int()` returns its integer equivalent. However, passing a non-numeric string (like `"hello"`) or a string representing a floating-point number (like `"3.14"`) will raise a `ValueError`. To write robust applications, it is standard practice to wrap casting operations in a `try-except` block to gracefully handle unexpected inputs.
Beyond standard base-10 conversion, the `int()` function accepts an optional `base` argument. This allows you to easily parse strings representing numbers in different number systems, such as binary (base 2), octal (base 8), or hexadecimal (base 16). For example, `int("1010", 2)` correctly parses the binary string into the decimal integer `10`, making it a versatile tool for lower-level or specialized mathematical programming.
Step-by-Step Implementation
- 1
Pass the numeric string to the built-in int() function.
- 2
Wrap your casting operations in try...except ValueError blocks to handle invalid formats.
- 3
Provide a second argument (e.g., base=16) to convert string values written in other bases.
Code Example
This script demonstrates converting a string to an integer, handling exceptions, and converting different base representations.
# 1. Standard base-10 conversion
num_str = "123"
num = int(num_str)
print(f"Standard conversion: {num} (Type: {type(num).__name__})")
# 2. Handling invalid input gracefully
invalid_str = "abc"
try:
result = int(invalid_str)
except ValueError:
print(f"Could not convert '{invalid_str}' to an integer.")
# 3. Converting from different bases (binary and hex)
binary_str = "1011"
hex_str = "ff"
print("Binary '1011' to decimal:", int(binary_str, 2))
print("Hex 'ff' to decimal:", int(hex_str, 16))Standard conversion: 123 (Type: int)
Could not convert 'abc' to an integer.
Binary '1011' to decimal: 11
Hex 'ff' to decimal: 255Frequently Asked Questions
How can I convert a float string like '12.34' to an integer?
You must first convert it to a float, then to an int: int(float("12.34")). Calling int("12.34") directly raises a ValueError.
How do I check if a string can be safely converted to an int?
You can use the .isdigit() string method, but note that it returns False for negative signs or whitespace. A try-except block is the most robust way.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Strings
Master string manipulation in Python. Learn string methods, slicing, concatenation, and formatting techniques with clear, executable code examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.