askvity

How do you convert a string to an integer in Python?

Published in Python Conversion 3 mins read

To convert a string to an integer in Python, use the built-in int() function.

The int() function is a fundamental tool in Python for type conversion. It attempts to interpret a string as a whole number and return its integer representation.

Using the int() Function

Here's the basic syntax:

integer_value = int(string_value)

Example:

string_number = "123"
integer_number = int(string_number)

print(integer_number)  # Output: 123
print(type(integer_number)) # Output: <class 'int'>

In this example, the string "123" is successfully converted to the integer 123.

Handling Errors

If the string cannot be directly converted to an integer (e.g., it contains non-numeric characters or is a floating-point number), the int() function will raise a ValueError. You can handle this using a try-except block.

string_value = "123.45" # Contains decimal
string_value2 = "abc"   # Contains non-numeric characters

try:
  integer_value = int(string_value)
  print(integer_value)
except ValueError:
  print("Invalid input: Cannot convert to an integer.")

try:
    integer_value = int(string_value2)
    print(integer_value)
except ValueError:
    print("Invalid input: Cannot convert to an integer.")

Specifying the Base (Radix)

The int() function can also accept an optional second argument, base, which specifies the base of the number in the string. This is useful for converting strings representing numbers in different numeral systems (e.g., binary, hexadecimal).

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

print(decimal_value)  # Output: 10

hexadecimal_string = "1A"
decimal_value = int(hexadecimal_string, 16) # Base 16 (hexadecimal)

print(decimal_value)  # Output: 26

Considerations

  • Leading/Trailing Whitespace: The int() function automatically ignores leading and trailing whitespace in the string.

    string_with_spaces = "  456  "
    integer_value = int(string_with_spaces)
    print(integer_value) # Output: 456
  • Floating-Point Numbers: Attempting to convert a string representing a floating-point number directly to an integer using int() will raise a ValueError. You might first need to convert it to a float using float() and then to an integer (which will truncate the decimal part), or round it using the round() function.

    float_string = "3.14"
    
    try:
        integer_value = int(float_string)
    except ValueError:
        float_value = float(float_string)
        integer_value = int(float_value) # Truncates the decimal
        print(integer_value) # Output: 3

In summary, the int() function is a versatile tool for converting strings to integers in Python, providing options for handling different bases and potential errors.

Related Articles