Data Type Conversion
Explore how to use Python's built-in functions to convert between data types such as integers, floats, and strings. Understand practical examples and when to apply these conversions to manage data effectively in your programs.
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.
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.