Convert String to Int Python
In Python, strings can be converted into an integer using built-in functions like ‘int()’, ‘eval()’, ‘str.isdigit()’, etc. However, it’s important to note that the string must represent a valid integer value for the conversion to succeed.
We will look at methods to change datatype from string to int in Python.
Example
Input: str_num = "1001"
Output: 1001
Explanation: In this, we are converting string into integer
How to Convert String to Int?
There are several built-in functions in PythonSeveral built-in functions in Python that let you convert strings to numbers. These functions take a string as its argument and return the corresponding integer value.
Convert String to Number Methods
We have explained the methods to convert a string into a integer datatype. Here is the list of the functions:
- Using int() function
- Using eval() function
- Using ast.literal_eval
- Using str.isdigit() function
Convert string to int using int() Function
Here we will use int() function that will return the int data type.
Python3
num = '10'
print ( type (num))
converted_num = int (num)
print ( type (converted_num))
print (converted_num + 20 )
|
Output
<class 'str'>
<class 'int'>
30
As a side note, to convert to float, we can use float() in Python
Convert string to int using Eval() Function
Here we will use eval() methods to Convert String to Int
Python3
a = "100"
print ( eval (a) + 12 )
|
String to Int Converter using Ast.literal_eval
This function evaluates an expression node or a string consisting of a Python literal or container display.
Python3
from ast import literal_eval
int_value = literal_eval( "1234" )
print (int_value)
print ( type (int_value))
|
Output
1234
<class 'int'>
Convert string to int using str.isdigit() Method
Python isdigit() function returns a boolean value TRUE if all the values in the input string are digits else it returns FALSE.
Python3
string = "42"
if string.isdigit():
integer = int (string)
print (integer)
else :
print (f "{string} is not a valid integer." )
|
Note: float values are decimal values that can be used with integers for computation.
We have covered the methods to convert string to int in Python. You can use any of the mentioned methods to change the data type of the variable from string to integer.
Similar Reads:
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...