How to convert a string to an int in Python

Convert a string to an int

The data types int and string are two primitive data types in Python.

Note: You can read more on data types in Python here.

Python has a built-in method int() that can be used to convert a string to an integer. It can take a string in any number system and convert it to an integer with base 10.

Syntax

The general syntax for the int() method is as follows:

int(value, base [optional])

Parameters

The int() method takes in two parameters:

  • value: This is the string object that we need to convert.

  • base: This is an optional parameter that specifies the number system. The default value is 10 which represents a decimal number. We can also provide it with a value of 2 to represent a binary number.

Convert a decimal number

If we need to convert a decimal number, the following code can be used:

string_to_convert = "135"
converted_int = int(string_to_convert)
print("The type after conversion is:", type(converted_int))
print("The integer is:", converted_int)

Explanation

  • Line 2: We call the int() method.

  • Line 4: We print the type of the converted integer.

  • Line 5: We print the converted integer.

We can see when we run the code above that the type of the converted_int variable is now int. Since the default value of base for the int() method is 10, we can also rewrite the code above as follows:

string_to_convert = "135"
converted_int = int(string_to_convert, 10)
print("The type after conversion is:", type(converted_int))
print("The integer is:", converted_int)

Convert a binary number

The int() method can also be used to convert a binary number to an integer. For this, we need to specify the value of base as 2, as follows:

string_to_convert = "10001"
base = 2
converted_int = int(string_to_convert, base)
print("The type after conversion is:", type(converted_int))
print("The integer is:", converted_int)

Explanation

  • Lines 1–2: We specify the string and the number system (base).

  • Line 3: We call the int() method which handles the conversion.

  • Line 5: We print the variable type.

  • Line 6: We print the converted number.

Note: The code above can also be used to convert other number systems to integers by specifying the value of the base. For example, we can convert a string that represents a hexadecimal number to an integer by setting the value of base to 16.

Copyright ©2024 Educative, Inc. All rights reserved