Casting in Python
? Casting in Python (Type Conversion)
Casting in Python is the process of converting one data type into another. Python provides built-in functions for explicit type conversion.
? Types of Casting
1?? Integer Casting (int())
Converts values to an integer.
print(int(3.9)) # 3 (Float to Int - removes decimal)print(int("10")) # 10 (String to Int)print(int(True)) # 1 (Boolean to Int)print(int(False)) # 0 (Boolean to Int)2?? Float Casting (float())
Converts values to a floating-point number.
print(float(5)) # 5.0 (Int to Float)print(float("3.14")) # 3.14 (String to Float)print(float(True)) # 1.0 (Boolean to Float)3?? String Casting (str())
Converts values to a string.
print(str(100)) # "100" (Int to String)print(str(3.14)) # "3.14" (Float to String)print(str(True)) # "True" (Boolean to String)4?? Boolean Casting (bool())
Converts values to True or False.
? Falsy Values: 0, 0.0, "", [], {}, None ? False
? Truthy Values: Everything else ? True
print(bool(0)) # Falseprint(bool(1)) # Trueprint(bool("")) # Falseprint(bool("Hello")) # Trueprint(bool([])) # False (Empty list)print(bool([1, 2])) # True (Non-empty list)5?? List, Tuple, Set Casting
Convert between different data structures.
print(list("abc")) # ['a', 'b', 'c'] (String to List)print(tuple([1, 2, 3])) # (1, 2, 3) (List to Tuple)print(set([1, 2, 2, 3])) # {1, 2, 3} (List to Set - removes duplicates)? Key Takeaways
? Use int(), float(), str(), and bool() for number and string conversions.
? Use list(), tuple(), set() for data structure conversions.
? Be careful when converting non-numeric strings to numbers (e.g., int("abc") will cause an error).
Want an example of a specific type? ?