Python Casting
Learn how to convert between different data types in Python using casting.
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
Casting in Python is therefore done using constructor functions:
int()- constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)float()- constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)str()- constructs a string from a wide variety of data types, including strings, integer literals and float literals
Integers
Example
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3 Floats
Example
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2 Strings
Example
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0' Type Conversion Examples
Converting to Integer
# From float to int
num_float = 9.8
num_int = int(num_float)
print(num_int) # Output: 9
# From string to int
str_num = "123"
num_int = int(str_num)
print(num_int) # Output: 123
# From boolean to int
bool_val = True
num_int = int(bool_val)
print(num_int) # Output: 1 Converting to Float
# From int to float
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
# From string to float
str_num = "3.14"
num_float = float(str_num)
print(num_float) # Output: 3.14
# From boolean to float
bool_val = False
num_float = float(bool_val)
print(num_float) # Output: 0.0 Converting to String
# From int to string
num_int = 42
str_num = str(num_int)
print(str_num) # Output: '42'
# From float to string
num_float = 3.14159
str_num = str(num_float)
print(str_num) # Output: '3.14159'
# From list to string
my_list = [1, 2, 3]
str_list = str(my_list)
print(str_list) # Output: '[1, 2, 3]' Common Casting Errors
Be careful when casting, as some conversions may raise errors:
Invalid String to Integer
# This will raise a ValueError
x = int("hello") # ValueError: invalid literal for int() Invalid String to Float
# This will raise a ValueError
y = float("abc") # ValueError: could not convert string to float Safe Casting with Error Handling
def safe_int_cast(value):
try:
return int(value)
except ValueError:
print(f"Cannot convert '{value}' to integer")
return None
# Usage
result = safe_int_cast("123") # Returns 123
result = safe_int_cast("hello") # Prints error message, returns None Advanced Casting
Boolean Casting
# Converting to boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("text")) # True
print(bool([])) # False
print(bool([1, 2])) # True List and Tuple Casting
# Converting between list and tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3, 4)
my_tuple = (5, 6, 7, 8)
my_list = list(my_tuple)
print(my_list) # [5, 6, 7, 8]
# Converting string to list
text = "hello"
char_list = list(text)
print(char_list) # ['h', 'e', 'l', 'l', 'o']