Type Casting in Python: Converting Data Types with Ease

Claudio Sabato
5 min readApr 19

Have you heard about type casting in Python and would like to know more? You are in the right place to learn about it.

The process of converting one Python data type to another data type is called type casting. Type casting can be useful when you want to ensure that your data is compatible with specific functions or operations (e.g. converting a variable to a string before concatenating it to another string).

In this tutorial we will go through the Python functions you can use to convert data types in the way you need.

Let’s discover type casting!

How Do You Do Type Casting in Python?

Python provides four built-in functions that can be used for type casting. These functions are:

  • str()
  • int()
  • float()
  • bool()

Each one of these functions if applied to a value returns the value converted into a different data type, respectively a string, an integer, a float, or a boolean.

One important thing to consider is that not all values can be cast to all data types. For example, if you try to convert a string that doesn’t represent a number to an int or float you will see a ValueError.

Here is the ValueError raised by the Python interpreter if you try to convert an invalid numeric string to an integer.

>>> incorrect_number = '34%'
>>> int(incorrect_number)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '34%'

And here is the error you get when trying to convert an incorrect numeric string to a float.

>>> float(incorrect_number)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '34%'

How to Typecast an int to a string in Python

To convert an integer to a string you can use the Python str() function. If x is the int you want to convert then use str(x) to obtain it in string format.

Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!