Casting in Python

  • Last updated Apr 25, 2024

Casting refers to explicitly changing data type of a value or variable from one type to another. For example, changing from int to string or string to int.

There are constructor functions in Python such as str(), int(), float() to change from one data type to another.

Casting to String

The str() function is used to change from any data type such as int type or float type to string type.

Example:

x = 10
y = 20.28

#change from int to string
a = str(x)

#change from float to string
b = str(y)

print(type(a))
print(type(b))

Output:

<class 'str'>
<class 'str'>
Casting to int

The int() function is used to change from string literal or float type to int type.

Example:

a = "10"
b = 20.28

#change from string to int
x = int(a)

#change from float to int
y = int(b)

print(type(x))
print(type(y))

Output:

<class 'int'>
<class 'int'>
Casting to float

The float() function is used to change from string literal or int type to float type.

Example:

x = 10
y = 20.28

#change from int to string
a = str(x)

#change from float to string
b = str(y)

print(type(a))
print(type(b))

Output:

<class 'float'>
<class 'float'>
Casting to bool

The bool() function is used to change from int or string literal to boolean type.

Example:

x = 0
y = "1"

#change from int to boolean
a = bool(x)

#change from string to boolean
b = bool(int(y))

print(type(a))
print(type(b))
print(a)
print(b)

Output:

<class 'bool'>
<class 'bool'>
False
True
Casting to complex

The complex() function is used to convert a string, int or float value to complex type. This method accepts two optional arguments and returns a complex number. The first parameter is referred to as a real part, whereas the second is referred to as an imaginary part.

Example:

a = "177"
b = 50
c = 140.64

#convert from string to complex using single parameter
print(complex(a))

#convert from int to complex using double parameters
print(complex(b, 5))

#convert from float to complex using double parameters
print(complex(c, 7))

Output:

(177+0j)
(50+5j)
(140.64+7j)

Note: A complex number cannot be converted into int or float type.