Python Type Casting: int(), float() and str() Explained - Python with AI tutorial chapter 8
Python

Python Type Casting: int(), float() and str() Explained

Python with AI Tutorial · Chapter 8 of 48

Python type casting means converting a value from one data type to another, for example turning the text "250" into the integer 250 so you can add to it. The main casting functions are int(), float(), str() and bool(), plus list(), tuple(), set() and dict() for collections. This chapter shows when each one is needed and how to avoid the errors they raise.

Why casting matters

Data that arrives from outside your program is almost always text. A CSV file, a web form, a database export and the input() function all hand you strings, even when the characters are digits. Python will not silently treat "5" as a number the way Excel sometimes does, so you must convert explicitly. That strictness prevents the classic spreadsheet bug where a column of numbers stored as text quietly sums to zero.

qty_from_form = "5"
print(qty_from_form + qty_from_form)       # string joining
print(int(qty_from_form) + int(qty_from_form))  # arithmetic
Output:
55
10

int(): convert to a whole number

int() accepts a string of digits (with optional sign and surrounding spaces), a float or a boolean. From a float it truncates toward zero rather than rounding, so int(19.99) is 19, not 20.

print(int("250") + 50)
print(int("  88  "))
print(int(19.99))
print(int(-7.8))
print(int(True))
Output:
300
88
19
-7
1
Common mistake: int("12.5") raises ValueError because the string is not a whole number. Convert in two steps: int(float("12.5")) gives 12. If you want proper rounding, use round(float("12.5")) instead.

float(): convert to a decimal

float() is more forgiving than int(). It accepts integers, digit strings with or without a decimal point, scientific notation and even "inf". It is the usual choice when parsing prices or percentages from text.

print(float("19.99"))
print(float(7))
print(float("1e3"))
print(float("  42.5 "))
print(float("12"))
Output:
19.99
7.0
1000.0
42.5
12.0

str(): convert to text

str() turns any value into its text form. You need it whenever you join a number onto a string with +, because Python refuses to concatenate str and int. Later you will use f-strings, which call str() for you, but understanding the explicit version first makes the error message obvious when you see it.

invoice_total = 1500.5
print("Total: " + str(invoice_total))
print(len(str(2026)))
print(str(True), str(None), str([1, 2]))
Output:
Total: 1500.5
4
True None [1, 2]

Without str() the first line fails with TypeError: can only concatenate str (not "float") to str. When you see that message, a missing str() is almost always the cause.

bool(): truthy and falsy values

bool() converts anything to True or False using a simple rule: empty or zero things are False, everything else is True. That includes the surprising case bool("False"), which is True because the string is not empty.

Value bool(value) Reason
0, 0.0 False Zero of any numeric type
"" False Empty string
[], (), {} False Empty collection
None False Absence of a value
42, -1, 0.01 True Any non-zero number
"False", "0", " " True Non-empty string, whatever it says
print(bool(0), bool(""), bool([]), bool(None))
print(bool(42), bool("False"))

shipped_text = "True"
shipped = shipped_text == "True"   # the safe way to parse a flag
print(shipped, type(shipped))
Output:
False False False False
True True
True <class 'bool'>

Casting a row of CSV data

Here is the pattern you will repeat for the rest of your Python life: read a row of strings, cast each field to its proper type, then calculate. Everything before the cast is text; everything after is real data.

row = ["INV-1041", "3", "249.99", "True"]

invoice_no = row[0]              # already a string
quantity = int(row[1])
unit_price = float(row[2])
is_paid = row[3] == "True"

line_total = quantity * unit_price
print(invoice_no, "total:", round(line_total, 2), "paid:", is_paid)
Output:
INV-1041 total: 749.97 paid: True

Cleaning text before casting

Real exports contain thousands separators, currency symbols and stray spaces. int() and float() tolerate spaces but nothing else, so strip the extras first with string methods. The strings chapter covers these methods fully.

raw_amount = "Rs 1,250"
cleaned = raw_amount.replace("Rs", "").replace(",", "").strip()
print(int(cleaned) + 500)

raw_pct = "12.5%"
print(float(raw_pct.rstrip("%")) / 100)
Output:
1750
0.125

Casting between collections

The collection constructors convert one container into another. list() makes an editable copy, set() removes duplicates, tuple() freezes a list and dict() builds a lookup from pairs.

print(list("ABC"))
print(list(range(1, 6)))
print(set(["Pune", "Delhi", "Pune"]))
print(tuple([45000, 52000]))
print(dict([("North", 45000), ("South", 52000)]))
Output:
['A', 'B', 'C']
[1, 2, 3, 4, 5]
{'Pune', 'Delhi'}
(45000, 52000)
{'North': 45000, 'South': 52000}

Set order is not guaranteed, so your set() line may print the cities the other way round. That is normal; sets have no order.

Implicit conversion

Python does a little casting for you, but only between number types. Mixing int and float gives a float, bool behaves as 0 or 1 in arithmetic, and / always produces a float. It never converts between text and numbers automatically.

print(5 + 2.0)
print(True + 1)
print(7 / 2, type(7 / 2).__name__)
Output:
7.0
2
3.5 float
Try it with AI

Feed the assistant messy real-world values and have it write a robust conversion function, then test the function yourself with your own awkward inputs.

Write a Python 3.12 function to_number(text) that converts messy strings from a spreadsheet export into a float. It must handle values like "1,250", "Rs 3,499.50", "12.5%", " 42 ", "(500)" meaning negative 500, and return None for blank or non-numeric text such as "N/A". Explain each cleaning step in a comment, then show the output for all six examples.
Try it with AI

Ask for an explanation of a casting error you are likely to meet, so the message makes sense when it appears in your own terminal.

I ran this Python code and got an error. Explain the error message in plain English, tell me which line caused it and why, and show two different correct versions (one using str() and one using an f-string):

units = 12
price = 45.5
print("Order value: " + units * price)

Common mistakes

  • Calling int() on a decimal string such as "12.5". Go through float() first.
  • Expecting int() to round. It truncates; use round() when you need nearest-whole-number behaviour.
  • Trusting bool("False"). Any non-empty string is True; compare the text explicitly instead.
  • Forgetting to remove commas and currency symbols before casting: ValueError: invalid literal for int() with base 10: '1,250'.
  • Concatenating a number to a string without str(), producing TypeError.

Exercise

A form submits the values ["12", "45.5", "3"] for quantity, unit price and discount percentage. Cast each to the right type, calculate the order value after discount and print it rounded to 2 decimals, followed by the type of each converted variable.

Show answer
form = ["12", "45.5", "3"]
quantity = int(form[0])
unit_price = float(form[1])
discount_pct = int(form[2])

order_value = quantity * unit_price * (1 - discount_pct / 100)
print(round(order_value, 2))
print(type(quantity).__name__, type(unit_price).__name__, type(discount_pct).__name__)
Output:
529.62
int float int

Related chapters

FAQ

What is type casting in Python?

Type casting is converting a value from one data type to another using a constructor function such as int(), float(), str() or bool(). It is explicit in Python; the language never converts between text and numbers on its own.

Why does int(“12.5”) give a ValueError?

int() only parses strings that represent whole numbers. Convert the text to a float first with float(“12.5”) and then to an int, or use round() if you want the nearest whole number rather than truncation.

How do I convert a string to a number in Python?

Use int(text) for whole numbers and float(text) for decimals. Strip spaces, commas and currency symbols first with .strip() and .replace(), because only plain digits, a sign and a decimal point are accepted.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 8 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com