Python - Casting
In Python, casting (or type conversion) refers to converting a variable from one data type to another. This is useful when working with different data types and needing a specific type for operations, comparisons, or formatting. Python offers built-in functions for casting between common data types like integers, floats, and strings.
In this guide, we’ll cover:
Implicit vs. Explicit Casting
Common Casting Functions in Python
Casting Complex Types
Implicit vs. Explicit Casting
Implicit Casting
Implicit casting is done automatically by Python, often when mixing compatible types. For example, in mathematical expressions, Python can automatically convert an integer to a float to ensure the result is accurate.
x = 10 # integer
y = 2.5 # float
result = x + y # x is implicitly cast to a float
print(result) # Output: 12.5 (float)
Here, x is implicitly converted to a float so that the addition can be performed with accurate precision.
Explicit Casting
Explicit casting is when you manually convert a variable to a specific type using casting functions. This is necessary when you need a particular type for an operation or function, and Python doesn't perform the conversion automatically.
x = "10" # string
y = int(x) # cast x to an integer
print(y + 5) # Output: 15
Common Casting Functions in Python
1. int(): Convert to Integer
The int() function converts a value to an integer. This is often used for converting strings of numbers or floats to integers. Non-numeric characters in strings will raise an error.
# String to integer
x = "123"
y = int(x) # y = 123 (integer)
# Float to integer (truncates decimal)
z = int(3.7) # z = 3
Note: int() truncates the decimal part without rounding.
2. float(): Convert to Float
The float() function converts a value to a float, which is useful when you need decimal precision in arithmetic operations.
# Integer to float
x = 10
y = float(x) # y = 10.0
# String to float
z = float("7.5") # z = 7.5
3. str(): Convert to String
The str() function converts values of any type into strings, which is helpful for concatenating text, logging, or formatting output.
x = 123
y = str(x) # y = "123" (string)
# Converting a float to a string
z = str(5.67) # z = "5.67"
4. bool(): Convert to Boolean
The bool() function converts a value to True or False. By default, the following values are False:
0
0.0
"" (empty string)
None
[], {}, () (empty collections)
All other values are True.
print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool("")) # Output: False
print(bool("hello")) # Output: True
5. list(), tuple(), and set(): Convert to Collection Types
You can use list(), tuple(), and set() to convert sequences and iterables into the respective collection types.
# String to list
x = "hello"
y = list(x) # y = ['h', 'e', 'l', 'l', 'o']
# List to tuple
a = [1, 2, 3]
b = tuple(a) # b = (1, 2, 3)
# List to set (removes duplicates)
c = [1, 2, 2, 3]
d = set(c) # d = {1, 2, 3}
Casting Complex Types
Casting Between Strings and Bytes
Python also supports casting between str (strings) and bytes, which is especially useful in data processing and networking.
encode(): Converts a string to bytes.
decode(): Converts bytes to a string.
# String to bytes
s = "hello"
b = s.encode("utf-8") # b = b'hello'
# Bytes to string
s2 = b.decode("utf-8") # s2 = "hello"
Casting Dictionary Keys and Values
You can convert dictionary keys and values to lists or other collections using list(), set(), or tuple():
my_dict = {'a': 1, 'b': 2}
# Keys to list
keys_list = list(my_dict.keys()) # keys_list = ['a', 'b']
# Values to tuple
values_tuple = tuple(my_dict.values()) # values_tuple = (1, 2)