Question
How to Parse a String to int or float in Python
Question
How can I convert a string to a float in Python?
For example:
"545.2222" # -> 545.2222
How can I convert a string to an int?
For example:
"31" # -> 31
I want to understand the correct way to parse numeric strings into Python number types.
Short Answer
By the end of this page, you will know how to convert numeric strings into int and float values in Python using the built-in int() and float() functions. You will also learn how these conversions behave, how to handle invalid input, and when to choose one numeric type over the other.
Concept
In Python, values read from places like user input, files, APIs, and CSV data often arrive as strings. Even if a string looks like a number, such as "31" or "545.2222", Python still treats it as text until you explicitly convert it.
The main tools for this are:
int()for whole numbersfloat()for decimal numbers
Examples:
age = int("31")
price = float("545.2222")
This matters because numbers and strings behave differently:
"3" + "4" # "34" (string concatenation)
3 + 4 # 7 (numeric addition)
If you do not convert a numeric string first, your program may produce the wrong result or raise an error.
A few important rules:
int("31")works because the string represents a valid integer.float("545.2222")works because the string represents a valid floating-point number.int("545.2222")fails because that string is not a valid integer literal.
Mental Model
Think of a string as a label on a box, and a number as the actual item inside the box.
"31"is a text label containing the characters3and131is an actual integer value that Python can do math with
The functions int() and float() are like unpacking tools:
int()opens the box and turns the text into a whole numberfloat()opens the box and turns the text into a decimal number
If the label does not describe a valid number, Python cannot unpack it and raises an error.
Syntax and Examples
Basic syntax
int(string_value)
float(string_value)
Convert a string to an integer
count = int("31")
print(count)
print(type(count))
Output:
31
<class 'int'>
Convert a string to a float
price = float("545.2222")
print(price)
print(type(price))
Output:
545.2222
<class 'float'>
Converting user input
user_age = int(input("Enter your age: "))
print(user_age + 1)
Step by Step Execution
Consider this example:
text = "42"
number = int(text)
result = number + 8
print(result)
Step-by-step
-
text = "42"- The variable
textstores a string, not a number.
- The variable
-
number = int(text)- Python reads the string
"42". - It recognizes that this is a valid integer representation.
- It converts it to the integer
42.
- Python reads the string
-
result = number + 8- Now
numberis an integer. - Python performs numeric addition:
42 + 8. - The result is
50.
- Now
-
print(result)- The program prints:
Real World Use Cases
String-to-number conversion appears everywhere in Python programs.
User input
quantity = int(input("How many items? "))
Used in command-line tools, scripts, and beginner programs.
Reading CSV or text files
row = ["Alice", "29", "88.5"]
age = int(row[1])
score = float(row[2])
CSV data is often read as strings first.
API responses
Some APIs send numbers as strings:
data = {"price": "19.99"}
price = float(data["price"])
Configuration values
Environment variables are strings by default:
import os
port = int(os.getenv("PORT", "8000"))
Data cleaning
When processing imported data, numeric fields may need conversion before sorting, filtering, or calculating totals.
Real Codebase Usage
In real projects, developers rarely convert values blindly. They usually combine conversion with validation and error handling.
Validation before use
value = "42"
number = int(value)
if number > 0:
print("Valid positive number")
Guarding against bad data
def parse_age(text):
try:
return int(text)
except ValueError:
return None
This pattern is common when reading forms, query parameters, files, or API payloads.
Early return pattern
def process_discount(text):
try:
discount = float(text)
except ValueError:
return "Invalid discount value"
if discount < 0:
return "Discount cannot be negative"
return discount
Common Mistakes
1. Forgetting that input() returns a string
Broken code:
age = input("Enter age: ")
print(age + 1)
This fails because age is a string.
Correct version:
age = int(input("Enter age: "))
print(age + 1)
2. Using int() on a decimal string
Broken code:
value = int("12.5")
This raises ValueError.
Correct version:
value = float("12.5")
Or, if you intentionally want an integer:
value = int(float())
Comparisons
| Concept | Purpose | Example | Result |
|---|---|---|---|
int() | Convert to whole number | int("31") | 31 |
float() | Convert to decimal number | float("31") | 31.0 |
str() | Convert to string | str(31) | "31" |
int() vs float()
Cheat Sheet
Quick reference
int("31") # 31
float("31") # 31.0
float("545.2222")# 545.2222
str(31) # "31"
Rules
int()converts valid integer strings to integers.float()converts valid numeric strings to floating-point numbers.input()always returns a string.int("12.5")raisesValueError.int(12.5)returns12by truncation.round(12.5)is for rounding, not parsing.
Safe parsing pattern
try:
num = int(text)
except ValueError:
num = None
Common conversions
FAQ
How do I convert a string to an integer in Python?
Use int():
num = int("31")
How do I convert a string to a float in Python?
Use float():
num = float("545.2222")
Why does int("12.5") fail?
Because "12.5" is not a valid integer string. Parse it with float() first if needed.
Does input() return a number in Python?
No. input() always returns a string.
What error happens if the string is not numeric?
Python raises ValueError.
Does int() round numbers?
No. It truncates the decimal part.
Can float() parse whole numbers too?
Mini Project
Description
Build a small command-line calculator that asks the user for two numbers as text, converts them into numeric values, and prints the sum. This demonstrates a very common real-world task: reading text input and parsing it into numbers before doing calculations.
Goal
Create a program that safely reads two numeric strings from the user, converts them to floats, and displays their total.
Requirements
- Ask the user to enter two numbers.
- Convert both inputs from strings to numbers.
- Use
float()so decimal values are allowed. - Print the sum of the two numbers.
- Handle invalid input without crashing.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.