November 5, 2024

Converting String to Integer in Python

In Python, converting a string to an integer is a common operation that can be done using the built-in int() function. This function takes a string or another number type and returns its integer representation.

1. Basic Conversion

The simplest case is converting a string that directly represents an integer:

string_num = "123"
integer_num = int(string_num)

print(integer_num)  # Output: 123
print(type(integer_num))  # Output: 
    

2. Handling Strings with Non-Numeric Characters

If the string contains non-numeric characters, attempting to convert it to an integer will raise a ValueError:

string_num = "123abc"

try:
    integer_num = int(string_num)
except ValueError as e:
    print("Error:", e)  # Output: Error: invalid literal for int() with base 10: '123abc'
    

3. Converting Strings with Different Number Bases

The int() function can also handle strings representing numbers in different bases. The second argument to int() specifies the base:

binary_string = "1010"
decimal_num = int(binary_string, 2)  # Base 2 (binary)

hex_string = "1A"
decimal_num_hex = int(hex_string, 16)  # Base 16 (hexadecimal)

print(decimal_num)  # Output: 10
print(decimal_num_hex)  # Output: 26
    

4. Stripping Whitespace

If the string includes leading or trailing whitespace, it can be safely stripped before conversion:

string_num = "  456  "
integer_num = int(string_num.strip())

print(integer_num)  # Output: 456
    

5. Using Try-Except for Safe Conversion

To handle cases where the conversion might fail, use a try-except block:

def safe_convert_to_int(string):
    try:
        return int(string)
    except ValueError:
        return None

print(safe_convert_to_int("789"))  # Output: 789
print(safe_convert_to_int("not_a_number"))  # Output: None
    

6. Conclusion

Converting strings to integers is straightforward with Python’s int() function. Be mindful of exceptions and handle cases where the string might not be convertible to an integer, especially when dealing with user input or data that might not be well-formed.