There are some times you need to specify the data type on to the variable, and this can be achieve type casting.
Object-oriented programming languages, including Python, use classes to define data types.
And defining data types can be done by calling the class constructor function.
int()
From an integer literal, int() constructs an integer number. From a float literal (by removing all decimals) or a string literal (provided string represents a whole number), int() constructs an integer number.
float()
From an integer literal or string integer literal, float() constructs a float number.
str()
The str() constructor constructs a string from different data types, including strings, integers, and floats.
number_a = int(100)
number_b = int(100.111)
number_c = int("100")
print(number_a)
print(number_b)
print(number_c)
100
100
100
In the above example, you can see by using the int()
constructor we are casting integer, float, and string.
number_a = float(100)
number_b = float(100.111)
number_c = float("100")
number_d = float("100.111")
print(number_a)
print(number_b)
print(number_c)
print(number_d)
100.0
100.111
100.0
100.111
Here, we cast integers, float, and strings by using the float()
constructor.
number_a = str(100)
number_b = str(100.111)
number_c = str("Falcon 10")
print(number_a)
print(number_b)
print(number_c)
'100'
'100.111'
'Falcon 10'
In the above example, the str()
constructor is used to cast integers, floats, and strings. You will get string data type (<'class' 'str'>
) if you check the data type of all variables after casting.