How to Convert String to Int in Python

Here are four ways to convert a string to int in Python:

  1. Using int() method
  2. Using eval() method
  3. Using ast.literal_eval() method
  4. Using str.isdigit() method

Method 1: Using int() method

Visual Representation

Visual Representation of Using int() method

# 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

Visual Representation of Using eval() method

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

Visual Representation of Using ast.literal_eval() method

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

Visual Representation of Using str.isdigit() method

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.

2 thoughts on “How to Convert String to Int in Python”

  1. 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,

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.