0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert String to Integer Easily

Use the built-in int() function to convert a string to an integer in Python, like int('123').
📋

Examples

Input'123'
Output123
Input'0'
Output0
Input'-456'
Output-456
🧠

How to Think About It

To convert a string to an integer, think of the string as a number written on paper. You want to tell Python to read that paper and understand it as a number, not just letters. The int() function does exactly that by taking the string and turning it into a number you can use for math.
📐

Algorithm

1
Take the string input that represents a number.
2
Use the conversion function to change the string into an integer.
3
Return or use the integer value for further operations.
💻

Code

python
string_number = '123'
integer_number = int(string_number)
print(integer_number)
Output
123
🔍

Dry Run

Let's trace converting the string '123' to an integer.

1

Input string

string_number = '123'

2

Convert to integer

integer_number = int('123') # becomes 123

3

Print result

print(123) # outputs 123

StepValue
1'123' (string)
2123 (integer)
3Output: 123
💡

Why This Works

Step 1: Using int() function

The int() function reads the string and converts it into an integer type.

Step 2: String must be numeric

The string should only contain digits (and optionally a leading minus sign) for int() to work without error.

Step 3: Result is a number

After conversion, you get a number that can be used in math or other operations.

🔄

Alternative Approaches

Using eval()
python
string_number = '123'
integer_number = eval(string_number)
print(integer_number)
Works but unsafe if input is not trusted because eval runs any code.
Using ast.literal_eval()
python
import ast
string_number = '123'
integer_number = ast.literal_eval(string_number)
print(integer_number)
Safer than eval, only evaluates literals like numbers and strings.

Complexity: O(n) time, O(1) space

Time Complexity

The int() function processes each character once, so time grows linearly with string length.

Space Complexity

Conversion uses constant extra space since it creates a single integer value.

Which Approach is Fastest?

int() is the fastest and safest for converting strings to integers compared to eval() or ast.literal_eval().

ApproachTimeSpaceBest For
int()O(n)O(1)Simple, safe string to int conversion
eval()O(n)O(1)Quick but unsafe for untrusted input
ast.literal_eval()O(n)O(1)Safe evaluation of literals including numbers
💡
Always ensure the string contains only digits before converting to avoid errors.
⚠️
Trying to convert a string with letters or symbols using int() causes a ValueError.