In this shot, we’ll learn how to convert a variable value from one data type to another.
We can convert a variable value from one data type to another data type by casting. Python, being an object-oriented programming language, uses classes to define data types. Casting can be done in Python with constructor functions. The table below shows a list of some constructor functions in Python.
Constructor function | Description | Example |
---|---|---|
str() |
String data type constructor that helps construct a string from various data types that can include float literals, integer literals, strings, etc. | string(2) will become '2' |
int() |
Integer data type constructor that helps construct an integer from various data types including float literals, string literals, and integer literals. | int(3.2) will become 3 |
float() |
Float data type constructor that helps construct float numbers from string literals, integer literals, and float literals. | float(3) will become 3.0 |
Let’s see some examples of how to specify the data type of a variable value.
Let’s look at how to specify a string type.
# creating the variables and specifying the data type we want as a valuex = str(2)y = str(5.8)z = str("3")# returning our outputprint("The value of str(2) is: ", x)print("The value of str(5.8) is: ", y)print('''The value of str("3") is:''', z)
Let’s look at how to specify an integer type.
# creating the variables and specifying the data type we want as a valuex = int(2)y = int(5.8)z = int("3")# returning our outputprint("The value of int(2) is: ", x)print("The value of int(5.8) is: ", y)print('''The value of int("3") is:''', z)
Let’s look at how to specify a float type.
# creating the variables and specifying the data type we want as a valuex = float(2)y = float(5.8)z = float("3")# returning our outputprint("The value of float(2) is: ", x)print("The value of float(5.8) is: ", y)print('''The value of float("3") is:''', z)
To change or convert the variable value of any data type to another data type, we must use the int()
, float()
or str()
constructor functions.