Type Casting in Python
In Python 3, type casting is the process of converting one data type to another data type. This is useful when you need to work with values of different data types, and you want to ensure that the values are compatible with the operations you want to perform.
You can use the following functions to perform type casting in Python:
int(x)
: Convertsx
to an integer.float(x)
: Convertsx
to a floating-point decimal.complex(x)
: Convertsx
to a complex number.str(x)
: Convertsx
to a string.bool(x)
: Convertsx
to a boolean value (True
orFalse
).
Here's an example:
x = 42
y = float(x)
z = str(y)
print(x, type(x))
print(y, type(y))
print(z, type(z))
In this example, the integer value 42
is first converted to a floating-point decimal using float(x)
, then converted to a string using str(y)
. The resulting values and their data types are printed to the standard output.
NOTE: It's important to note that not all values can be converted to all data types. For example, you can't convert the string "hello"
to an integer using int("hello")
, because the string doesn't represent a valid integer. In such cases, a ValueError
will be raised.