Type casting
Casting means converting a value from one type to another. Python never converts between text and numbers silently, so you will do this often, especially with user input and file data.
The constructor functions
| Function | Converts to | Notes |
|---|---|---|
int(x) | integer | Truncates floats, parses whole number strings |
float(x) | float | Parses decimal strings |
str(x) | string | Works on anything |
bool(x) | boolean | See the truthiness rules in the Booleans lesson |
list(x), tuple(x), set(x) | collection | Works on any iterable |
Numbers to numbers
print(int(3.99)) # 3, decimal part dropped
print(int(-3.99)) # -3, truncates towards zero
print(float(7)) # 7.0
print(round(3.99)) # 4, if you want rounding insteadStrings to numbers
age = int("21")
price = float("49.99")
print(age + 1, price * 2)Whitespace around the number is fine, but anything else raises a ValueError:
print(int(" 42 "))
try:
int("42 rupees")
except ValueError as e:
print("Error:", e)int("3.7") also fails because the string is not a whole number. Convert to float first if you need to: int(float("3.7")).
Numbers to strings
The most common need is building a message. str() works, but f-strings are cleaner:
count = 3
print("You have " + str(count) + " new messages")
print(f"You have {count} new messages")Strings and lists
print(list("hello"))
print("".join(["h", "e", "l", "l", "o"]))
print("a,b,c".split(","))Between collections
numbers = [3, 1, 3, 2, 1]
print(set(numbers)) # removes duplicates
print(tuple(numbers))
print(sorted(set(numbers))) # unique and orderedReading input
input() always returns a string, even if the user types digits. Cast it before doing maths.
raw = input("How many tickets? ")
tickets = int(raw)
print("Total:", tickets * 250, "rupees")Practice
- Convert the string
"3.14159"to a float, multiply by 2, and print the result rounded to 3 decimal places. - Take the list
["10", "20", "30"]and produce the integer sum 60. - What does
bool("False")return? Run it and explain why.
