Type Casting
In this tutorial you will learn about type casting in python – implicit and explicit. In this article, you will see various ways for type casting. Thorough understanding can be helpful in everyday Python programming.
Type casting (aka type conversion) is the process of converting the value of one data type to another data type. It can be useful when a certain operation makes use of a specific data type. Python has two types of type casting:
- Implicit Type Casting
- Explicit Type Casting
Implicit Type Casting
In implicit type casting, Python automatically casts the value of one data type into another one. Here is an example:
# Implicit Type Casting
num = 5 # Pyhton defines num to be an int
print (num) # num is converted to string
Explicit Type Casting
In explicit type casting, the user specifies the required data type, using predefined casting functions.
How to Convert to int
In order to convert objects to int we use the int() function. We can convert string to int, convert float to int, etc. When coverting float to int, the number is rounded down. Here is an example:
# Convert to int
# Convert string to int
my_str = "1982"
my_num = int(my_str)
print(my_num)
# Convert float to int
my_float = 10.9
new_num = int(my_float)
print(new_num)
How to Convert to string
In order to convert objects to string we use the str() function. We can convert int to string, convert list to string, etc. Here is an example:
# Convert to string
# Convert int to string
my_num = 1982
my_str = str(my_num)
print(my_str)
# Convert list to string
my_list = [1, 2, 3, 4]
list_string = str(my_list)
print(list_string)
How to Convert to float
In order to convert objects to float we use the float() function. We can convert int to float, convert string to float, etc. Here is an example:
# Convert to float
# Convert string to float
my_str = "1982"
my_num = float(my_str)
print(my_num)
# Convert int to float
my_float = 10
new_num = int(my_float)
print(new_num)
How to Convert to list
In order to convert objects to list we use the list() function. We can only convert iterables to list - string, tuple, etc. Here is an example:
# Convert to list
# Convert string to list
my_str = "1982"
my_list = list(my_str)
print(my_list)