Table of Contents
ToggleType casting in Python refers to converting an object of one data type into another. Python supports two types of casting: implicit and explicit. Implicit casting is done automatically by Python, while explicit casting requires the use of built-in functions like int(), float(), and str(). In this guide, we’ll explore both types of casting with examples.
Implicit casting occurs automatically when Python converts a smaller data type to a larger one to avoid data loss. For example, when adding an integer and a float, Python implicitly converts the integer to a float.
a = 10 # int
b = 10.5 # float
c = a + b # int is implicitly cast to float
print(c) # Output: 20.5
Explanation: The integer a is implicitly cast to a float before the addition.
Explicit casting is done manually using Python’s built-in functions. The most commonly used functions are int(), float(), and str().
int() FunctionThe int() function converts a float, string, or boolean to an integer. If the string contains a valid integer representation, it will be converted; otherwise, a ValueError is raised.
a = int(10.5) # Converts float to int
b = int("100") # Converts string to int
c = int(True) # Converts boolean to int
print(a, b, c) # Output: 10 100 1
float() FunctionThe float() function converts an integer, string, or boolean to a float. If the string contains a valid floating-point representation, it will be converted; otherwise, a ValueError is raised.
a = float(10) # Converts int to float
b = float("10.5") # Converts string to float
c = float(True) # Converts boolean to float
print(a, b, c) # Output: 10.0 10.5 1.0
str() FunctionThe str() function converts an integer, float, or boolean to a string. It can also convert other objects like lists and tuples to their string representations.
a = str(10) # Converts int to string
b = str(10.5) # Converts float to string
c = str(True) # Converts boolean to string
print(a, b, c) # Output: "10" "10.5" "True"
When using explicit casting, ensure that the data being converted is compatible with the target type. For example, converting a string like "Hello" to an integer will raise a ValueError.
Type casting is a powerful feature in Python that allows you to convert data from one type to another. Whether you’re working with numbers, strings, or other data types, understanding how to use implicit and explicit casting will help you write more flexible and efficient code.
Happy coding! 🚀
