Skip to content
Related Articles
Open in App
Not now

Related Articles

Convert string to integer in Python

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 28 Feb, 2023
Improve Article
Save Article

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers. Below is the list of possible ways to convert an integer to string in python:

1. Using int() function

Syntax: int(string)

Example: 

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 

Python3




num = '10.5'
 
# check and print type num variable
print(type(num))
 
# convert the num into string
converted_num = float(num)
 
# print type of converted_num
print(type(converted_num))
 
# We can check by doing some mathematical operations
print(converted_num + 20.5)

Output

<class 'str'>
<class 'float'>
31.0

2. Using float() function

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer)

Syntax: float(string)

Example: 

Python3




a = '2'
b = '3'
 
# print the data type of a and b
print(type(a))
print(type(b))
 
# convert a using float
a = float(a)
 
# convert b using int
b = int(b)
 
# sum both integers
sum = a + b
 
# as strings and integers can't be added
# try testing the sum
print(sum)

Output

<class 'str'>
<class 'str'>
5.0

3. converting python string to int using eval() function

Python3




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

Output

112

4. converting python string to float using eval() function

Python3




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

Output

112.0

5. Using ast.literal_eval

Python3




from ast import literal_eval
 
int_value = literal_eval("1234")
print(int_value)
print(type(int_value))

Output

1234
<class 'int'>

6. Using str.isdigit() 

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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!