Python is a dynamically typed language, which means that the type of a variable is determined at runtime based on the value it contains. However, there may be times when you want to explicitly convert a variable from one type to another. This process is known as casting.
Casting in Python is a way of changing the type of an object. For instance, you might have a string that you want to use as an integer or an integer that you want to use as a string. Python provides built-in functions for casting objects to different types, and these functions are used extensively in Python programming.
Here are some examples of casting in Python:
- Casting integers to strings
To cast an integer to a string, you can use the str() function. For example:
num = 123 string_num = str(num) print(string_num) # Output: '123'
- Casting strings to integers
To cast a string to an integer, you can use the int() function. For example:
string_num = '123' num = int(string_num) print(num) # Output: 123
Note that if the string contains non-numeric characters, you will get a ValueError. You can also specify the base of the number by passing a second argument to the int() function. For example, to convert a hexadecimal string to an integer:
hex_num = '0xFF' num = int(hex_num, 16) print(num) # Output: 255
- Casting floats to integers
To cast a float to an integer, you can use the int() function as well. However, this will truncate the decimal part of the float. For example:
float_num = 3.14 num = int(float_num) print(num) # Output: 3
- Casting integers to floats
To cast an integer to a float, you can use the float() function. For example:
num = 123 float_num = float(num) print(float_num) # Output: 123.0
- Casting strings to floats
To cast a string to a float, you can use the float() function. For example:
string_num = '3.14' float_num = float(string_num) print(float_num) # Output: 3.14
Note that like with int(), if the string contains non-numeric characters, you will get a ValueError.
In conclusion, Python casting is a useful feature that allows you to change the type of an object. It is important to remember that when casting, you should ensure that the object being cast can be converted to the desired type, or else you may encounter errors.