Tuesday, September 24, 2024
Google search engine
HomeLanguagesConvert String to Int Python

Convert String to Int Python

In Python an strings can be converted into an integer using the Python built-in function. However, it’s important to note that the string must represent a valid integer value for the conversion to succeed.

Example

Input: str_num = "1001"
Output: 1001 
Explanation: In this, we are converting string into integer

Python Convert String to Int

In Python, you can convert a string into an integer using different functions in Python. This function takes a string as its argument and returns the corresponding integer value.

  • Using int() function
  • Using eval() function
  • Using ast.literal_eval
  • Using str.isdigit() function

Convert a string to a number Method

String to Int converter using int() function in Python

Here we will use int() function which 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 

String to Int Converter 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'>

String to Int Converter using str.isdigit() 

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.

RELATED ARTICLES

Most Popular

Recent Comments