Question

How to Parse a String to int or float in Python

pythonparsingfloating-pointtype-conversioninteger

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 numbers
  • float() 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.
  • int(545.2222) works, but it truncates the decimal part.

Converting strings to numbers is a basic and essential skill in Python because real programs constantly process external data.

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 characters 3 and 1
  • 31 is 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 number
  • float() 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.

Take Quiz

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)

Since input() returns a string, int() is needed before doing arithmetic.

Converting decimal text

temperature = float("23.5")
print(temperature * 2)

Converting a float-like string to an int

This does not work:

int("12.9")

It raises an error because "12.9" is not a valid integer string.

If you really want to convert it, parse it as a float first, then convert:

value = int(float("12.9"))
print(value)

Output:

12

This truncates the decimal part.

Step by Step Execution

Consider this example:

text = "42"
number = int(text)
result = number + 8
print(result)

Step-by-step

  1. text = "42"

    • The variable text stores a string, not a number.
  2. number = int(text)

    • Python reads the string "42".
    • It recognizes that this is a valid integer representation.
    • It converts it to the integer 42.
  3. result = number + 8

    • Now number is an integer.
    • Python performs numeric addition: 42 + 8.
    • The result is 50.
  4. print(result)

    • The program prints:
50

Another example with float()

text = "5.5"
number = float(text)
result = number * 2
print(result)

What happens

  1. text contains the string "5.5"
  2. float(text) converts it to the float 5.5
  3. 5.5 * 2 gives 11.0
  4. The output is:
11.0

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.

Take Quiz

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

Configuration parsing

import os
debug_level = int(os.getenv("DEBUG_LEVEL", "1"))

Data pipelines

Developers often parse text fields into numbers before calculations, filtering, or aggregation.

prices = ["10.5", "20.0", "7.25"]
parsed_prices = [float(p) for p in prices]
print(sum(parsed_prices))

This is common in analytics, reporting, and backend processing.

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("12.5"))

3. Assuming conversion always succeeds

Broken code:

score = int("hello")

This raises ValueError because "hello" is not numeric.

Safer version:

text = "hello"
try:
    score = int(text)
except ValueError:
    print("Not a valid integer")

4. Confusing truncation with rounding

int(12.9)   # 12

int() does not round. It removes the decimal part.

If you want rounding:

round(12.9)   # 13

5. Mixing strings and numbers

Broken code:

price = "10"
total = price + 5

Correct version:

price = int("10")
total = price + 5

Comparisons

ConceptPurposeExampleResult
int()Convert to whole numberint("31")31
float()Convert to decimal numberfloat("31")31.0
str()Convert to stringstr(31)"31"

int() vs float()

Featureint()float()
Stores decimalsNoYes
Accepts "31"YesYes
Accepts "31.5"NoYes
Output example3131.0 or 31.5

Examples

int("31")      # 31
float("31")    # 31.0
float("31.5")  # 31.5

int() vs round()

FunctionInputOutputMeaning
int(12.9)12.912Truncates decimal part
round(12.9)12.913Rounds to nearest integer

Use int() when you want conversion to an integer type. Use round() when you want numeric rounding behavior.

Take Quiz

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") raises ValueError.
  • int(12.5) returns 12 by truncation.
  • round(12.5) is for rounding, not parsing.

Safe parsing pattern

try:
    num = int(text)
except ValueError:
    num = None

Common conversions

age = int("25")
price = float("19.99")
count = int(input("Count: "))

Watch out for

  • Empty strings: int("") fails
  • Non-numeric text: float("abc") fails
  • Decimal strings with int(): int("3.14") fails
  • String math vs numeric math: "3" + "4" is "34"

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?

Yes.

float("31")  # 31.0
Take Quiz

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

  1. Ask the user to enter two numbers.
  2. Convert both inputs from strings to numbers.
  3. Use float() so decimal values are allowed.
  4. Print the sum of the two numbers.
  5. Handle invalid input without crashing.
Take Quiz

Keep learning

Related questions

View more