Python Casting

Casting is the conversion of a variable data or an object from one data type to another. For example, converting from int to string or string to int.

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

str()

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

Example

x = 10
y = 20.28

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

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

print(type(a))
print(type(b))
  
Output:
<class 'str'>
<class 'str'>

int()

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

Example

a = "10"
b = 20.28

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

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

print(type(x))
print(type(y))
  
Output
<class 'int'>
<class 'int'>

float()

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

Example

x = 10
y = 20.28

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

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

print(type(a))
print(type(b))
  
Output
<class 'float'>
<class 'float'>

bool()

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

Example

x = 0
y = "1"

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

#convert 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