Type casting in Python

Explicit conversion

To cast a variable to a string just use the str() function.

my_str = str('32') # this is just a regular explicit intialization
print(my_str)

my_str = str(32) # int to str
print(my_str)

my_str = str(32.0) # float to str
print(my_str)

To cast a variable to an integer just use the int() function.

my_int = int(32) # this is just a regular explicit intialization
print(my_int) #output: 32

my_int = int(3.2) # float to int: rounds down to 3
print(my_int) #output: 3

my_int = int('32') # str to int
print(my_int) #output: 32

To cast a variable to a float just use the float() function.

my_float = float(3.2)   # this is just a regular explicit intialization
print(my_float) #output: 3.2

my_float = float(32)     # int to float
print(my_float) #output: 32.0

my_float = float('32')  # str to float
print(my_float) #output: 32.0

What I did before is called explicit type conversion.

In some cases you don’t need to do the conversion explicitly, Python can do it by itself.

Implicit conversion

The example below shows the implicit conversion when adding an int and a float.

Notice that my_sum is a float. Python uses float to avoid data loss since the int type can not represent the decimal digits.

my_int = 32
my_float = 3.2

my_sum = my_int + my_float

print(my_sum) # output: 35.2

print(type(my_sum)) # <class 'float'>

On the other hand, in this example, when you add an int and a str, Python will not be able to make the implicit conversion, and the explicit type conversion is necessary.

my_int = 32
my_str = '32'

my_sum = my_int + int(my_str) # explicit conversion works
print(my_sum)# output: 64

my_sum = my_int + my_str # implicit conversion throws an error
#output:
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#TypeError: unsupported operand type(s) for +: 'int' and 'str'

The same error is thrown when trying to add float and str types without making the explicit conversion.

my_float = 3.2
my_str = '32'

my_sum = my_float + float(my_str) # explicit conversion works
print(my_sum)# output: 35.2

my_sum = my_float + my_str # implicit conversion throws an error
#output:
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#TypeError: unsupported operand type(s) for +: 'float' and 'str'