Converting Data Types in Python

Type conversion is used to converting one data type to another. For example, it is common to convert a string to an int or vice versa. This can be done with Python’s built-in functions such as int (), str () or float ()

Python and many other code languages are so-called typed languages. This means that we need to keep track of what data type variables have as we use them for different operations. If the problem that an operation cannot be performed due to the data types does not match, we can simply solve the problem by using built-in methods in Python.

 

Let’s see a short example on why it is important to keep track of the data type a variable contains

 

a = "1"
b = 2
print(a+b)

Will lead to an Error and cause the program to crash, because you cannot add an int to a string (add an integer to a text string).

Type conversion is used to convert one data type to a different one

This problem is solved by casting (converting) one data type to another. Python has built-in features that allow you to directly convert one data type to another.

CONVERT DATA TYPE IN PYTHON – EXAMPLE

Let’s take the same variables as we used in the previous example, and show how to convert the variable a (of the data type string), to the data type int

 

a = "1"
b = 2 
print(int(a)+b)

Note the highlighted code, Using the function int (), the variable a is converted from a string to an int, which makes the operation feasible!

 

Additionally, the corresponding operations can be done with:

  • str () – converts a variable to a string
  • float () – converts a variable to a float

Keep in mind on what you are trying to convert

Note that all conversions will not succeed. For example, the following code will not work:

 

a = "2.3"
int(a)

will cause an error since 2.3 is not an int (integer) but a float.

 

However, the following code works fine

 

a = "2.3"
float(a)