Typecasting is the process of converting one data type into another data type. In Python, typecasting can be done using the following methods:
-
int() - This function is used to convert a number or a string to an integer.
-
float() - This function is used to convert a number or a string to a float.
-
str() - This function is used to convert a number or a boolean value to a string.
-
bool() - This function is used to convert a number or a string to a boolean value (True or False).
For example:
x = 10
y = "20"
# convert x to a float
z = float(x)
# convert y to an integer
w = int(y)
# convert w to a string
a = str(w)
# convert z to a boolean value
b = bool(z)
In the above example, the value of x is an integer and it is converted to a float and stored in z. The value of y is a string and it is converted to an integer and stored in w. The value of w is then converted to a string and stored in a. Finally, the value of z is converted to a boolean value and stored in b.
Master the art of Data Science with Python and unlock the power of insights.