Data Type Conversion in Python
Sometimes, we need to convert data types in Python, and this can generally be achieved by simply using the data type's name as a function.
Python provides two types of data type conversion:
Implicit Type Conversion - Handled automatically
Explicit Type Conversion - Requires the use of conversion functions
Implicit Type Conversion
In implicit type conversion, Python automatically converts one data type to another without our intervention.
In the example below, we perform operations on two different data types, and the lower data type (integer) is converted to the higher data type (floating point) to prevent data loss.
Example
num_int = 123 num_flo = 1.23 num_new = num_int + num_flo print("num_int data type:", type(num_int)) print("num_flo data type:", type(num_flo)) print("num_new value:", num_new) print("num_new data type:", type(num_new))
Output:
num_int data type: <class 'int'> num_flo data type: <class 'float'> num_new value: 124.23 num_new data type: <class 'float'>
Code Explanation:
In this example, we add two different data types, num_int
and num_flo
, and store the result in num_new
. We then check the data types of these variables.
In the output, we see that num_int
is an integer, num_flo
is a float, and the new variable num_new
is also a float. This happens because Python automatically converts smaller data types to larger ones to avoid data loss.
Let's look at another example where an integer is added to a string:
Example
num_int = 123 num_str = "456" print("num_int data type:", type(num_int)) print("num_str data type:", type(num_str)) print(num_int + num_str)
Output:
num_int data type: <class 'int'> num_str data type: <class 'str'> Traceback (most recent call last): File "/runoob-test/test.py", line 7, in <module> print(num_int + num_str) TypeError: unsupported operand type(s) for +: 'int' and 'str'
As shown in the output, trying to perform arithmetic operations between an integer and a string causes a TypeError
. Python cannot perform implicit conversion in this case.
However, Python provides a solution called explicit conversion for these scenarios.
Explicit Type Conversion
In explicit type conversion, users convert the data type of an object to the desired data type. We use predefined functions like int()
, float()
, and str()
to perform explicit type conversion.
Converting to Integer: int()
Example
x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3
Converting to Float: float()
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
Converting to String: str()
Example
x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'
To perform arithmetic between integers and strings, you can use explicit conversion.
Example
num_int = 123 num_str = "456" print("num_int data type:", type(num_int)) print("Before conversion, num_str data type:", type(num_str)) num_str = int(num_str) # Explicitly converting to integer print("After conversion, num_str data type:", type(num_str)) num_sum = num_int + num_str print("The sum of num_int and num_str is:", num_sum) print("The data type of sum is:", type(num_sum))
Output:
num_int data type: <class 'int'> Before conversion, num_str data type: <class 'str'> After conversion, num_str data type: <class 'int'> The sum of num_int and num_str is: 579 The data type of sum is: <class 'int'>
Here are some built-in functions that can convert between data types. These functions return a new object representing the converted value.
Function | Description |
---|---|
int(x [,base]) | Converts x to an integer |
float(x) | Converts x to a floating-point number |
complex(real [,imag]) | Creates a complex number |
str(x) | Converts object x to a string |
repr(x) | Converts object x to an expression string |
eval(str) | Evaluates a valid Python expression in a string and returns an object |
tuple(s) | Converts a sequence s to a tuple |
list(s) | Converts a sequence s to a list |
set(s) | Converts to a mutable set |
dict(d) | Creates a dictionary, d must be a sequence of (key, value) tuples |
frozenset(s) | Converts to an immutable set |
chr(x) | Converts an integer to a character |
ord(x) | Converts a character to its integer value |
hex(x) | Converts an integer to a hexadecimal string |
oct(x) | Converts an integer to an octal string |