Type Casting in python
Similar to type conversion, type casting is explicitly specifying the data type of a value or variable using constructor functions like , int(), or float().
str()
Type casting in Python means converting one data type into another data type. It is useful when you need to perform operations that require a specific type of data.
Why Use Type Casting?
Sometimes data is stored in a format that is not suitable for the operation you want to perform. Type casting helps convert the data into the required type.
Example:
str1 = "7"
str2 = "3.142"
str3 = "13"
num1 = 29
num2 = 6.67
print(int(str1))
print(float(str2))
print(float(str3))
print(str(num1))
print(str(num2))
Output:
7
3.142
13.0
29
6.67
Common Type Casting Functions
Python provides several built-in functions for type conversion:
| Function | Description |
|---|---|
|
Converts a value to an integer |
|
Converts a value to a floating-point number |
|
Converts a value to a string |
|
Converts a value to a boolean |
|
Converts a value to a list |
|
Converts a value to a tuple |
|
Converts a value to a set |
|
Converts a value to a dictionary |