Type Casting
Overview
Type casting (or type conversion) is the process of explicitly converting data from one primitive type to another. Since Python is strongly typed, it will not automatically convert a string to an integer if you try to add them together. You must use built-in constructor functions like int(), float(), str(), and bool() to manually perform these conversions.
Syntax
# String to Integer
age_str = "25"
age_int = int(age_str)
# Integer to Float
price = 10
price_float = float(price) # 10.0
# Number to String
score = 99
message = "Your score is: " + str(score)
# Falsy values cast to False
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # FalseCommon Pitfalls
Trying to cast a string that contains letters or decimal points directly to an integer (e.g.,
int("25.5")orint("hello")), which triggers a ValueError.Forgetting to cast numerical values to strings before concatenating them with other strings, which triggers a TypeError.
Interview Questions
What happens when you cast a float to an int using int()?
The int() function truncates the value towards zero. It chops off the decimal part completely rather than rounding. For example, int(3.99) becomes 3.
Real-World Example
Sanitizing and parsing raw user input from a web form or command line.
raw_input = " 1050.75 "
# 1. Clean whitespace using strip()
# 2. Cast to float to handle decimals
# 3. Finally cast to int to get a whole number
clean_amount = int(float(raw_input.strip()))
print(f"Processed amount: USD {clean_amount}") # 1050Check Your Knowledge
Test your understanding of Type Casting with these quick questions.