§ 2.2.2section 4 of 18·~4 min
Type conversion
Values read from a CSV file or an API are strings, even when they look like numbers. Convert them before you do any maths.
raw = "499"
print(raw + raw) # joins two strings
amount = int(raw)
print(amount + amount) # adds two numbers
print(float("12.5"), str(42), bool(""))
OUTPUT
499499
998
12.5 42 False| Function | Turns | Into |
|---|---|---|
int(x) | "42" | 42 |
float(x) | "12.5" | 12.5 |
str(x) | 42 | "42" |
bool(x) | "" or 0 | False |
If a conversion can't work, Python raises an error: int("abc") fails with a ValueError. Section 1.7 shows how to handle that without crashing.