Python casting allows variables to be specified by type. Since Python is not statically typed, but is an object oriented programming language it uses classes to define data types, including its primitive types. In Python, this can be done with functions such as int() or float() or str(). A very common pattern is that you convert a number, currently as a string into a proper number.
How is Casting Used in Python?
Constructor functions allow casting in Python as show below:
Constructor Functions
Data Type Float: float()
The float() constructs a float number from a float literal, an integer literal, or a string literal (providing the string represents a float or an integer).
Input:
1 2 3 4 5 6 7 8 9 | float1 = float(1) float2 = float(2.9) float3 = float('3') float4 = float('4.2') print(f"Casting float1 = float(1) constructs to {float1} ") print(f"Casting float2 = float(2.9)constructs to {float2} ") print(f"Casting float3 = float('3') constructs to {float3} ") print(f"Casting float4 = float('4.2') constructs to {float4}") |
Output:
1 2 3 4 | Casting float1 = float(1) constructs to 1.0 Casting float2 = float(2.9)constructs to 2.9 Casting float3 = float('3') constructs to 3.0 Casting float4 = float('4.2') constructs to 4.2 |
Data Type Integers – int()
The int() constructs an integer number from a float literal by rounding down to the previous whole number, float literal, or a string literal by providing the string that represents a whole number.
Input:
1 2 3 4 5 6 7 | int1 = int(1) int2 = int(2.9) int3 = int('3') print(f"Casting int1 = int(1) constructs to {int1} ") print(f"Casting int2 = int(2.9) constructs to {int2} ") print(f"Casting int3 = int('3') constructs to {int3} ") |
Output:
1 2 3 | Casting int1 = int(1) constructs to 1 Casting int2 = int(2.9) constructs to 2 Casting int3 = int('3') constructs to 3 |
Data Type String – str()
The str() constructs a string from a variety of data types. Some of these data types include float literals, integer literals and strings.
Input:
1 2 3 4 5 6 7 | str1 = str('Print a string.') str2 = str(2) str3 = str(3.0) print(f"Casting str1 = str('Print a string.') constructs to {str1} ") print(f"Casting str2 = str2 = str(2) constructs to {str2} ") print(f"Casting str3 = str('3') constructs to {str3} ") |
Output:
1 2 3 | Casting str1 = str('Print a string.') constructs to Print a string. Casting str2 = str2 = str(2) constructs to 2 Casting str3 = str('3') constructs to 3.0 |