Python Type Casting
Type casting means converting a value from one type to another, such as turning the text “42” from input() into the number 42. Python does some conversions for you, and you do the rest with built-in functions named after the types.
- Implicit vs explicit conversion
- Convert between numbers and strings
- Convert between collections
- Handle values that cannot be converted
Implicit conversion
When you mix an int and a float in arithmetic, Python converts the int to a float for you, so no precision is lost:
qty = 3 # intprice = 19.5 # floattotal = qty * priceprint(total, type(total).__name__)print(True + True) # bool is a kind of int: True is 158.5 float 2
Python will not guess between text and numbers. Mixing them is an error:
age = 30print("Age: " + age)Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Age: " + age)
~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to strExplicit conversion functions
| Function | Converts to | Example | Result |
|---|---|---|---|
int(x) | whole number | int("42"), int(9.8) | 42, 9 |
float(x) | decimal | float("3.5"), float(2) | 3.5, 2.0 |
str(x) | text | str(100) | '100' |
bool(x) | True/False | bool(0), bool("no") | False, True |
list(x) | list | list("abc") | ['a', 'b', 'c'] |
tuple(x) | tuple | tuple([1, 2]) | (1, 2) |
set(x) | set | set([1, 1, 2]) | {1, 2} |
dict(x) | dict | dict([("a", 1)]) | {'a': 1} |
Numbers and strings
age = 30print("Age: " + str(age)) # number to textprint(int("42") + 8) # text to numberprint(float("3.75") * 2)print(int(9.99), int(-9.99)) # int() truncates towards zeroprint(int(" 15\n")) # surrounding whitespace is ignoredAge: 30 50 7.5 9 -9 15
int() can also read numbers written in other bases:
print(int("ff", 16), int("0b1010", 0), int("777", 8))255 10 511
Values that cannot be converted
print(int("3.5"))Traceback (most recent call last):
File "main.py", line 1, in <module>
print(int("3.5"))
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'int() will not read a decimal string. Convert to float first, or catch the error:
print(int(float("3.5"))) for text in ["12", "4.0", "abc"]: try: print(text, "->", int(text)) except ValueError: print(text, "-> not a whole number")3 12 -> 12 4.0 -> not a whole number abc -> not a whole number
Converting to bool
bool() returns False for “empty” or zero values and True for everything else.
for v in [0, 0.0, "", "0", "False", [], [0], None]: print(f"{v!r:8} -> {bool(v)}")0 -> False 0.0 -> False '' -> False '0' -> True 'False' -> True [] -> False [0] -> True None -> False
bool("False") is True, because it is a non-empty string. To read a yes/no answer, compare the text: answer.strip().lower() in ("yes", "y", "true").
Between collections
letters = list("banana")print(letters)print(set(letters)) # duplicates removedprint(tuple(letters[:3]))print("".join(letters)) # list of strings back to one string pairs = [("chrome", 120), ("firefox", 118)]print(dict(pairs))print(list({"x": 1, "y": 2})) # a dict converts to its keys['b', 'a', 'n', 'a', 'n', 'a']
{'a', 'b', 'n'}
('b', 'a', 'n')
banana
{'chrome': 120, 'firefox': 118}
['x', 'y']Check your understanding
Predict the output
print(int("7") + float("2.5"), str(7) + str(2.5), int(True))9.5 72.5 1
int + float gives a float, str + str joins the text, and True converts to 1.
Quick quiz
1. What does int("3.9") do?
int() does not accept decimal strings. Use int(float("3.9")) to get 3.
2. What does bool("0") return?
Any non-empty string is truthy, even "0".
3. Which converts [3, 1, 3] to a collection with only unique items?
set([3, 1, 3]) is {1, 3}.
Exercise: sum numbers from text
A line of comma-separated numbers arrives as text. Convert it and print the total and the average.
"12, 7.5, 30, 0.5"
[12.0, 7.5, 30.0, 0.5] Total: 50.0 Average: 12.5
Hint 1
split(",") gives the parts as strings; float() converts each one.
line = "12, 7.5, 30, 0.5"numbers = [float(part) for part in line.split(",")]print(numbers)print("Total:", sum(numbers))print("Average:", sum(numbers) / len(numbers))[12.0, 7.5, 30.0, 0.5] Total: 50.0 Average: 12.5
split(",") leaves spaces around the parts, but float() ignores surrounding whitespace, so no strip() is needed.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python type casting FAQ
How do I convert a string to an integer in Python?
Use int("42"). If the string may contain a decimal point, use int(float(text)), and wrap it in try / except ValueError for user input.
How do I convert an integer to a string?
Use str(42), or put it in an f-string: f"{42}".
What is the difference between implicit and explicit type conversion?
Implicit conversion is done by Python automatically, such as int to float in 3 * 1.5. Explicit conversion is when you call a function such as int() or str() yourself.
How do I convert a list to a string?
Use ", ".join(items) for a list of strings. For other values, convert each one first: ", ".join(map(str, numbers)).