Python Type Casting
Satellite · Data Types
Type Casting
Python uses constructors (`int()`, `float()`, `str()`, etc.) for conversions. Learn the patterns and how to handle errors gracefully.
Common casts
| Operation | Example | Notes |
|---|---|---|
| String → int | int("42") | Raises ValueError if invalid |
| String → float | float("3.14") | Beware locale differences |
| Any → string | str(obj) | Calls __str__ |
| Iterable → list | list(range(3)) | Copies elements |
| Iterable → set | set(names) | Removes duplicates |
| Int ↔ float | float(5) / int(5.9) | int truncates toward zero |
Custom conversions
Implement __int__, __float__, __str__, or __bool__ methods to customize casting for your classes.
Error handling
try:
price = float(raw_price)
except ValueError:
raise ValueError("Invalid price provided")
Always validate user input before casting.