Python Casting
What is Type Casting?
Type casting (or type conversion) is the process of converting one data type to another. Python supports both implicit and explicit casting:
- **Implicit Casting**: Automatically performed by Python when safe (e.g., int + float → float)
- **Explicit Casting**: Manually done using constructor functions such as int(), float(), str(), etc.
Function | Converts To | Example |
---|---|---|
int() | Integer | int('42') → 42 |
float() | Floating-point | float(3) → 3.0 |
str() | String | str(3.14) → '3.14' |
bool() | Boolean | bool(1) → True |
list() | List | list('hello') → ['h','e','l','l','o'] |
tuple() | Tuple | tuple([1,2,3]) → (1,2,3) |
set() | Set | set([1,2,2,3]) → {1,2,3} |
Numeric Casting
⚠️ Warning: Casting non-numeric strings to numbers raises ValueError.
Example
# String to number
age = int("25")
price = float("9.99")
# Number to number
pi_int = int(3.14) # Truncates → 3
pi_float = float(3) # → 3.0
# Boolean to number
true_val = int(True) # → 1
false_val = float(False) # → 0.0
Output
# Results shown in comments
String Conversion
Example
# Number to string
str_age = str(25)
str_price = str(9.99)
# List to string
list_str = str([1,2,3]) # "[1, 2, 3]"
# Custom formatting
formatted = f"Price: {9.99:.2f}" # "Price: 9.99"
hex_str = hex(255) # '0xff'
bin_str = bin(42) # '0b101010'
ℹ️ Note: For custom string formatting, use f-strings or the format() method.
Collection Casting
⚠️ Warning: When converting dictionaries to sequences, only the keys are kept by default.
Example
# Between sequences
letters = list("hello") # ['h','e','l','l','o']
numbers = tuple([1,2,3]) # (1,2,3)
unique = set([1,2,2,3]) # {1,2,3}
# Dictionary conversions
pairs = dict([('a',1),('b',2)]) # {'a':1, 'b':2}
keys = list({'x':10, 'y':20}) # ['x', 'y']
Boolean Conversion
Any Python object can be evaluated as True or False depending on whether it is 'truthy' or 'falsy'.
Example
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False
print(bool("Hi")) # True
print(bool([])) # False
print(bool([1])) # True
print(bool(None)) # False
Output
False True False True False True False
ℹ️ Note: Empty sequences and collections are Falsy; non-empty ones are Truthy.
Special Cases
⚠️ Warning: Be cautious when chaining conversions—check each step to avoid errors or unexpected results.
Example
# Float precision issues
x = float("123.45678901234567890")
print(x) # 123.45678901234568 (precision loss)
# Base conversion
num = int("1010", 2) # Binary → 10
hex_num = int("FF", 16) # Hexadecimal → 255
# Chaining conversions
result = str(float(int("42"))) # "42.0"
Output
123.45678901234568 42.0
Practical Applications
- User input processing (inputs are always strings)
- API responses (e.g., converting JSON string values)
- Database operations (ensuring correct data types)
- Scientific computing (converting between numeric types)
Example
# Safe input handling
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Please enter a valid integer!")
# JSON data conversion
import json
data = json.loads('{"price": "9.99"}')
price = float(data['price']) # String → Float
ℹ️ Note: Always validate and sanitize external data before casting.
Exercises
Task | Example Input | Expected Output |
---|---|---|
Convert user weight (str) to float | "68.5" | 68.5 |
Create tuple from string chars | "python" | ('p','y','t','h','o','n') |
Convert list of strings to integers | ['1','2','3'] | [1, 2, 3] |
Safe boolean conversion | "False" | False |