Table of contents
- Python Data Type Conversion
- How to convert data types in Python?
Python Data Type Conversion
In python, data type conversion is when you convert one data type to another. You may encounter many situations when you need to convert one data type to another. There are two types of data type conversion in python. They are:
Implicit Data Type Conversion
When the python interpreter itself converts one data type to another, it is called implicit data type conversion. You as a programmer do not need to do anything in this type of type conversion.
int_num = 222 # integer flo_num = 222.222 # float new_num = flo_num + int_num # addition of integer and float print(type(new_num))
In the example above, when we add an integer and float data type and assign the result to a new variable new_num, the new_num’s data type will be a float. It is because the python interpreter always converts a smaller data type to large data type implicitly to avoid the loss of data.
Explicit Data Type Conversion
In some cases, python interpreter cannot convert data types implicitly and we have to convert the data type explicitly. This type of data type conversion is called an explicit data type conversion.
int_num = 222 str_num = '111' print(int_num + str_num)
The above program will give you typeerror because the python interpreter cannot convert the string data type (str_num = ‘111’) to integer implicitly. In this case, we need to convert the string to an integer first explicitly as:
int_num = 222 str_num = '111' new_str_num = int(str_num) print(int_num + new_str_num)
In the third statement, you can see that we converted the string data type to an integer using int() function. This is called the explicit data type conversion.
How to check data type with type() function?
In many situations, you may need to know what type class does the variable or object belongs to. Python has a type() function that checks the type class of an object.
li1 = [1, 2, 3, 4, 5] int_num = 1000 str_ex = 'yonep' print(type(li1)) print(type(int_num)) print(type(str_ex))
<class 'list'> <class 'int'> <class 'str'>
How to convert data types in Python?
Python provides many functions to convert one built-in data type to another. Some of the most used data type conversions are as follows:
Convert integer to float
float() function can convert an integer argument passed to it to a float data type.
a = 999 b = float(a) print(b)
Convert float to integer
To convert float data type to integer data type, you can use int() function.
a = 999.111 b = int(a) print(b)
Convert string to integer
The same int() function can also convert a string to an integer.
a = '999' b = int(a) print(b)
Convert integer or float to string
str() function can convert number types (both integer and float) to string data type. This function can also convert other object types to a string.
a = 9.9 b = 10 c = str(a) d = str(b) print(c) print(d)