Skip to main content

Casting

A variable's type is very important when you need to do specific operations on it.

For example, you cannot do the following:

x = "42"
y = 42

print(x + y) # INVALID

This will throw an error, since you cannot add a string x to an integer y.

Sometimes, you will need your variable to be a very specific type of data. When you need to do this, you will need to convert your variable from one type to another.

This is called casting.

info

In Python, there are three functions responsible for casting a variable to a specific type.

They are:

1. int()
2. float()
3. str()

int()

The most common use case is to convert a string to an integer. This is done with the int() function.

int-casting.py
a = "1"
b = 2

int(a) + b # 3

float()

If you want to convert an something to a float, you can use the float() function.

A cool application to this is converting infinity to a number.

float-casting.py
float("3.1415") # 3.1415

str()

If you want to convert something into a string, you can use the str() function.

str-casting.py
str(100) # "100"

The most common occurrences of casting are between integers and strings.