How do I convert a string to an integer in Python?
Benjamin C
benjamin c profile pic

In Python, you can convert a string to an integer using theint() function. Here's a detailed explanation of how to accomplish this:

1
2
3
4
5
6

string_number = "123"

integer_number = int(string_number)

print(integer_number)  # Output: 123

In the example above, theint() function is used to convert the string"123" to an integer. The resulting integer value is assigned to the variableinteger_number. It's important to note that theint() function will only work if the string contains a valid integer representation. If the string contains non-numeric characters or a decimal point, aValueError will be raised. To handle cases where the string may not be a valid integer, you can use error handling with atry-except block:

1
2
3
4
5
6
7
8

string_number = "123"

try:
    integer_number = int(string_number)
    print(integer_number)
except ValueError:
    print("Invalid integer format")

By using this error handling approach, you can catch and handle theValueError that may occur if the string is not a valid integer. Additionally, if you want to convert a string to an integer with a specific base (e.g., binary, octal, hexadecimal), you can provide the base as the second argument to theint() function:

1
2
3
4
5
6

string_binary = "1010"

integer_number = int(string_binary, 2)

print(integer_number)  # Output: 10

In this example,int(string_binary, 2) converts the binary string"1010" to an integer with base 2 (binary), resulting in the decimal value10. By using theint() function with or without a specified base, you can convert a string to an integer in Python. Keep in mind the format and content of the string to ensure successful conversion.