Python Type Casting
Type casting, also known as type conversion, is the process of converting one data type into another. Python provides several built-in functions for type casting. In this lesson, we will cover the most commonly used type casting functions in Python.
Integer Casting (int)
The int()
function can be used to convert a float or a string into an integer. For example:
x = int(3.14)
y = int("42")
Float Casting (float)
The float()
function can be used to convert an integer or a string into a float. For example:
x = float(5)
y = float("3.14")
String Casting (str)
The str()
function can be used to convert any data type into a string. For example:
x = str(42)
y = str(3.14)
Boolean Casting (bool)
The bool()
function can be used to convert any data type into a boolean value. For example:
x = bool(1)
y = bool("")
z = bool(0)
Conclusion
Type casting is a useful technique in Python for converting data from one type to another. By using the appropriate type casting functions, you can ensure that your data is in the correct format for your program's requirements.