Python Casting
Casting means converting a value from one type to another. In Python you do it by calling the type itself as a function: int(), float(), str(), bool(), list() and so on. Casting is everyday work, because data from files, web forms and the user almost always arrives as text.
The main conversion functions
| Function | Converts to | Example | Result |
|---|---|---|---|
int(x) |
integer | int("42") |
42 |
float(x) |
float | float("2.5") |
2.5 |
str(x) |
string | str(99) |
"99" |
bool(x) |
boolean | bool("") |
False |
list(x) |
list | list("hi") |
['h', 'i'] |
tuple(x) |
tuple | tuple([1, 2]) |
(1, 2) |
set(x) |
set | set([1, 1, 2]) |
{1, 2} |
To integers
int() accepts integers, floats and strings that contain a whole number. Converting a float simply drops the fractional part — it truncates toward zero, it does not round:
print(int(7.9))
print(int(-7.9))
print(int("123"))
print(int(" 56 ")) # surrounding spaces are fine
print(int(True))
print(int("ff", 16)) # a second argument gives the base7
-7
123
56
1
255
To floats
print(float(3))
print(float("4.75"))
print(float("1e3"))
print(float("inf"))3.0
4.75
1000.0
inf
To strings
str() turns almost anything into its text form. That's how you join numbers onto strings with +:
age = 30
height = 1.72
message = "Age " + str(age) + ", height " + str(height) + " m"
print(message)
print(str([1, 2, 3]))
print(len(str(2 ** 64))) # how many digits does 2**64 have?Age 30, height 1.72 m
[1, 2, 3]
20
When conversion fails
If the text doesn't look like a number, Python raises a ValueError. Note that int() will not accept a decimal string directly:
for text in ["17", "3.5", "twelve"]:
try:
print(text, "->", int(text))
except ValueError as err:
print(text, "-> error:", err)
print(int(float("3.5"))) # convert in two steps17 -> 17
3.5 -> error: invalid literal for int() with base 10: '3.5'
twelve -> error: invalid literal for int() with base 10: 'twelve'
3
Tip: Whenever you convert text that comes from outside your program, wrap it in
try/except ValueErrorso a typo doesn't crash everything.
Implicit conversion
Python converts automatically in a few safe situations, mainly arithmetic between numeric types. An int mixed with a float becomes a float, and True/False act as 1/0:
print(5 + 2.0)
print(True + True + True)
print(10 * False)7.0
3
0
Python will not silently convert between text and numbers — "5" + 2 is a TypeError. This strictness catches many bugs early.
A practical example
Data read from a CSV file is all strings. Casting turns it into something you can calculate with:
row = "Laptop,2,899.50"
name, qty_text, price_text = row.split(",")
qty = int(qty_text)
price = float(price_text)
print(name, "total:", qty * price)Laptop total: 1799.0
Test yourself
What does int(9.99) return?
- 10
- 9
- 9.99
- A ValueError
What happens with int("2.5")?
- Returns 2
- Returns 3
- Raises ValueError
- Returns 2.5
What is str(10) + str(5)?
- 15
- "105"
- "15"
- TypeError