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.

Implicit vs explicit conversion

Python implicitly widens numeric types in mixed expressions, but never converts strings for you:

3 + 4.0        # 7.0 — int promoted to float automatically
"3" + 4 # TypeError — no implicit str/int mixing
int("3") + 4 # 7 — you must cast explicitly

Everything else is explicit: you call a constructor to convert on purpose.

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

Casting gotchas

int("3.5")     # ValueError — int() won't parse a decimal string
int(3.5) # 3 — but it truncates a float fine
int("0xFF", 16) # 255 — pass a base to parse other number systems
bool("False") # True! — any non-empty string is truthy
bool(0) # False

That bool("False") result is a frequent bug: to parse a boolean from text, compare the string explicitly (value.strip().lower() == "true"), don't call bool() on it.

Custom conversions

Implement __int__, __float__, __str__, or __bool__ on your class to control how it casts:

class Money:
def __init__(self, cents): self.cents = cents
def __float__(self): return self.cents / 100
def __str__(self): return f"${self.cents / 100:.2f}"

Error handling

Casting user input can fail, so wrap it and fail with a clear message:

try:
price = float(raw_price)
except ValueError:
raise ValueError(f"Invalid price: {raw_price!r}")

For a quick default instead of an exception:

def to_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default

Always validate or guard external input before casting.

Next up in your learning path

Frequently Asked Questions

How do I convert a string to an integer in Python?

Use int("42"). It raises ValueError if the string is not a valid whole number, so wrap it in try/except when handling user input.

int("42")     # 42
int(" 42 ") # 42 — surrounding whitespace is fine
int("3.5") # ValueError
int("abc") # ValueError

Why does int("3.5") raise an error but int(3.5) works?

int() only parses strings that represent whole numbers, so the decimal string "3.5" is rejected. Given an actual float, int(3.5) truncates toward zero. To go from a decimal string to int, cast through float first.

int("3.5")          # ValueError
int(3.5) # 3 — truncates
int(float("3.5")) # 3

Why is bool("False") True?

bool() tests truthiness, and any non-empty string is truthy—including "False". To parse a boolean from text, compare explicitly.

bool("False")   # True — non-empty string!
bool("") # False

value = "false"
value.strip().lower() == "true" # False — correct way

What is the difference between implicit and explicit conversion?

Implicit conversion is done automatically by Python, such as promoting an int to a float. Explicit conversion (type casting) is when you call a constructor like int(), float(), or str() yourself. Python never converts strings to numbers implicitly.

3 + 4.0        # 7.0 — implicit int -> float
"3" + 4 # TypeError — no implicit str/int mixing
int("3") + 4 # 7 — explicit cast