In this lesson we will tackle the concept of casting in Python.

Casting is the operation that returns the value of an expression (or a variable) converted to another type. In fact, the variable remains of the original type anyway.

For example we can convert string in int, int in string, string in float, etc.

In the last lesson we already listed some data types in Python:

int – integers.

float – floating point (decimal).

Banner Pubblicitario

complex – complex numbers.

bool – boolean.

string – string.

These are just some types of data, we will study others later.

Python casting functions

The casting functions we will study today are:

  • int(): converts a variable to the integer data type;
  • str(): converts a variable to the given string type;
  • float(): converts a variable to the data type float, i.e. a decimal number.

Example on the casting operation in Python

Remember that strings must be written between single or double quotes. So if for example I write a = ’13 ‘, 13 is seen as a string and not as a number. Likewise if I write a = ”13 ″.

So here’s an example:

Banner pubblicitario

>>>a = ’13’ #in this case a is a string as there are quotes.

>>>a*2 #multiply the variable a by 2.

output: ‘1313’ #we will get the repetition of string 13 twice.

>>>a = int(a) #convert to full, doing the casting.

>>>a*2 #make the product of a by 2 again.

output: 26 #in this case we will get the product of 13 times 2.

What we did at this point: a = int(a) represents a casting operation.

In fact, the variable a initially contains a string but, with the int() casting operation, it is subsequently converted to an integer.

Second example casting Python:

The same can be done:

>>> b = 3 #in this case the variable b is an integer.

>>> b

3

>>> b = str(b)

>>> b

‘3’


b = '3'
print(b*3)
#casting - convert string to int
b = int(b)
print(b*3)

x = 1
y = 2

#casting - convert int to string
x = str(x)
y = str(y)
print(x + y)
print(b*3)

In this lesson we have made some examples of casting in Python.

Useful links

Python tutorial

Python Compiler

Install Python

Variables