Data Type Conversion
Learn about conversions between different data types in Python.
We'll cover the following
Conversions between data types
There are several different data types available in Python. Sometimes, you might come across a scenario where you need to perform conversions from one data type to another.
In Python, conversions between types can be made by using its built-in functions, a few of which are mentioned below.
Conversion Function | Description | Example |
---|---|---|
float() |
Converts the element passed to a floating-point number | float(123) , float("123") = 123.0 |
int() |
Converts the element passed to an integer | int(56.78) , int("56") = 56 |
str() |
Converts the element passed to a string | str(123) = “123” |
In Python, the built-in type()
function can be used to check the data type of variables.
Using this, let’s look at a few examples to get a better grasp of these built-in functions.
float_var = 56.78 # Float variableint_var = 123 # Integer variablestr_var = "123.2" # String variableres_int = int(float_var) # Converting float to integerprint(res_int)print("Type: ", type(res_int)) # Checking type of res_intres_str = str(float_var) # Converting float to stringprint(res_str)print("Type: ", type(res_str)) # Checking type of res_strres_ftr = float(str_var) # Converting string to floatprint(res_ftr)print("Type: ", type(res_ftr)) # Checking type of res_ftr
Although not its main functionality, the round()
function can also be used to convert data types. For example, round(56.78)
returns 57. Over here, the floating-point number is rounded to the nearest integer.
## Using round() for converting data types# Note, the 0 represents the number of decimals you want the number to be rounded off to.float_var = 56.78print(round(float_var, 0)) # We don't want any decimal numbers over here.