Skip to main content

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

OperationExampleNotes
String → intint("42")Raises ValueError if invalid
String → floatfloat("3.14")Beware locale differences
Any → stringstr(obj)Calls __str__
Iterable → listlist(range(3))Copies elements
Iterable → setset(names)Removes duplicates
Int ↔ floatfloat(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.

Next up in your learning path