Here are four ways to convert a string to int in Python:
- Using int() method
- Using eval() method
- Using ast.literal_eval() method
- Using str.isdigit() method
Method 1: Using int() method
Visual Representation
# String representation of an integer
string_value = "101"
print("Before conversion =======")
print(string_value)
print(type(string_value))
# Convert string to integer
integer_value = int(string_value)
print("After conversion =======")
print(integer_value)
print(type(integer_value))
Output
Before conversion =======
101
<class 'str'>
After conversion =======
101
<class 'int'>
Method 2: Using eval() method
Visual Representation
string_value = "101"
print(type(string_value))
integer_value = eval(string_value)
print(integer_value)
print(type(integer_value))
Output
<class 'str'>
101
<class 'int'>
Method 3: Using ast.literal_eval() method
The ast.literal_eval() is particularly useful when parsing data from untrusted sources or when you need to ensure that only safe literals are evaluated from a string.
Visual Representation
from ast import literal_eval
string_value = "101"
print(type(string_value))
integer_value = literal_eval(string_value)
print(integer_value)
print(type(integer_value))
Output
<class 'str'>
101
<class 'int'>
Method 4: Using str.isdigit() method
The str.isdigit() method is used to check if all characters in a string are digits. If all characters are digits, the method returns True; otherwise, it returns False.
Visual Representation
string_value = "101"
# Check if the string represents a number
if string_value.isdigit():
# Convert string to integer
integer_value = int(string_value)
print(integer_value)
print(type(integer_value))
else:
print(f"{string_value} is not a valid integer.")
Output
101
<class 'int'>
That’s it.
Hiral
Thanks for posting, this article was very helpful when converting string to int and vice versa. I came across a similar post though it was certainly not quite as thorough as this!
Thanks again,
uptoword
This is a great tutorial on how to convert a string to an integer in Python.