Open In App
Related Articles

Convert String to Int Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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:

  1. Using int() function
  2. Using eval() function
  3. Using ast.literal_eval
  4. 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'
 
# check and print type num variable
print(type(num))
 
# convert the num from string into int
converted_num = int(num)
 
# print type of converted_num
print(type(converted_num))
 
# We can check by doing some mathematical operations
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

# converting python string to
# int using eval() function
a = "100"
print(eval(a)+12)

                    

Output
112

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)  # Output: 42
else:
    print(f"{string} is not a valid integer.")

                    

Output
42

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
Previous
Next
Share your thoughts in the comments
Similar Reads