Type Conversion in Python
In Python, type conversion (also known as type casting) is the process of converting a value from one data type to another. This is a common necessity in programming. For instance, you might receive numerical data as strings from a user input form and need to convert them to int or float to perform mathematical calculations.
Python supports two main types of conversion:
- Implicit Type Conversion: This happens automatically by the Python interpreter when it needs to prevent data loss in operations involving different data types. For example, when you add an
intand afloat, Python will automatically convert theintto afloatto perform the addition. - Explicit Type Conversion: This is when you, the programmer, manually convert a variable’s type using built-in functions like
int(),str(),float(), etc.
Implicit Type Conversion
Let’s see an example where Python handles the conversion for you.
Pyground
Add an integer and a float. What is the data type of the result?
Expected Output:
The result is: 15.5 The type of the result is: <class 'float'>
Output:
Python automatically “upgrades” the int to a float to avoid losing the decimal part. This is a safe conversion. However, Python will not implicitly convert a float to an int as it could lead to data loss.
Explicit Type Conversion
Most of the time, you will need to perform explicit conversions using Python’s built-in functions.
Converting to Integer: int()
The int() function converts a value to an integer.
When converting a float to an int, the decimal part is truncated (not rounded).
num_float = 9.8
num_int = int(num_float)
print(num_int) # Output: 9Be careful! If you try to convert a string that cannot be interpreted as an integer (like "12.5" or "hello"), Python will raise a ValueError.
Converting to Float: float()
The float() function converts a value to a floating-point number.
Pyground
Convert an integer, a string, and a boolean to floats.
Expected Output:
From int: 100.0 From string: 3.14 From boolean: 1.0
Output:
Converting to String: str()
The str() function can convert almost any data type into its string representation. This is extremely useful for creating output messages that combine text and numbers.
Pyground
You have a name (string) and an age (integer). Combine them into a single sentence.
Expected Output:
My name is Alice and I am 30 years old. My name is Alice and I am 30 years old.
Output:
Converting to Other Collection Types
You can also convert between different collection types like lists, tuples, and sets.
list(): Converts a sequence (like a tuple or string) into a list.
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
my_string = "abc"
char_list = list(my_string)
print(char_list) # Output: ['a', 'b', 'c']When converting a list or tuple to a set, any duplicate elements will be removed.