Python course menu
Python Type Conversion: int(), float(), str(), bool() and Casting
Learn how to convert between types in Python: int, float, str, bool, list and tuple conversions, implicit vs explicit conversion, truthy and falsy values, and how to handle conversion errors.
On this page
Data often arrives in the wrong type. Numbers typed by a user, read from a file, or received from a website all arrive as text. Type conversion (also called casting) turns a value of one type into another so you can work with it.
Why conversion is needed#
age = "21"
print(age + 1)TypeError: can only concatenate str (not "int") to str"21" is text that happens to contain digits. Python will not guess what you mean, so you must convert it.
Converting with int(), float() and str()#
The type names double as conversion functions:
print(int("42") + 8) # text -> whole number
print(float("3.75")) # text -> decimal number
print(str(100) + " points") # number -> text
print(int(9.99)) # decimal -> whole number (cuts off decimals)
print(round(9.99)) # rounding instead
print(float(7)) # whole number -> decimal50
3.75
100 points
9
10
7.0int() also ignores surrounding spaces, and can read other number bases:
print(int(" 42 "))
print(int("101", 2)) # binary
print(int("ff", 16)) # hexadecimal42
5
255When conversion fails#
Text must actually look like the target type:
print(int("3.5"))ValueError: invalid literal for int() with base 10: '3.5'"3.5" is not a whole number. Convert in two steps:
print(int(float("3.5")))3You will learn to handle failures gracefully with try / except in Exceptions.
Implicit conversion#
Sometimes Python converts for you, when no information can be lost:
print(3 + 4.5)
print(type(3 + 4.5))
print(True + 2)7.5
<class 'float'>
3Mixing int and float gives a float. True and False behave as 1 and 0 in arithmetic. Python never converts text to numbers implicitly; that always needs int() or float().
bool(): truthy and falsy values#
bool() converts anything to True or False. Empty and zero values are falsy; almost everything else is truthy:
print(bool(0), bool(1), bool(""), bool("hi"),
bool([]), bool([0]), bool(None))False True False True False True FalseThis matters in if statements: if name: means "if name is not empty".
Converting collections#
print(list("abc"))
print(tuple([1, 2, 3]))
print(set([1, 1, 2]))
print(str([1, 2]))['a', 'b', 'c']
(1, 2, 3)
{1, 2}
[1, 2]set() removes duplicates, a common trick you will meet in Sets.
Common mistakes#
Practice#
Practice exercise
A shopping list stores prices as text: prices = ["120", "75.5", "300"]. Write a program that adds them up and prints Total: 495.50.
Show hint
Some prices have decimals, so convert each one with float() inside a loop, then format with :.2f.
Show solution
prices = ["120", "75.5", "300"]
total = 0
for p in prices:
total += float(p)
print(f"Total: {total:.2f}")Total: 495.50Using int() would fail on "75.5", which is why float() is the right choice here.
Key takeaway#
Finished this lesson?