What do you understand by Typecasting in Python with the help of examples?
Python
Computer Science Engineering
748
Deepak
In explicit type conversion, users convert the data type of an object to the required data type.
We use the predefined functions like int(), float(), complex(), bool(), str(), tuple), list(), dict(), etc. to perform explicit type conversion.
This type conversion is also called typecasting because the user casts (change) the data type of the objects.
Example:
a = 144
b = 144.0
c = 69
print('Variable a converted into string ', str(a) )
print('Variable a converted into float ', float(a))
print('Variable b converted into integer', int(b))
Typecasting in Python refers to the process of converting a value from one data type to another. This is done using built-in functions that are designed to handle the conversion of one data type to another. Here are some examples of typecasting in Python:
num = 123 string_num = str(num) print(string_num)
In this example, the integer value 123 is converted to a string using the str()
function.
string_num = "123" num = int(string_num) print(num)
In this example, the string value "123" is converted to an integer using the int()
function.
float_num = 123.456 int_num = int(float_num) print(int_num)
In this example, the float value 123.456 is converted to an integer using the int()
function. The decimal part of the float is truncated, so the resulting integer value is 123.
string = "Hello, World!" list_string = list(string) print(list_string)
In this example, the string "Hello, World!" is converted to a list using the list()
function. Each character in the string becomes an element in the list.
Typecasting is a useful technique in Python as it allows you to convert data from one type to another, which can be necessary for performing certain operations or working with different libraries and modules.