Intermediate Typecasting
In programming, Typecasting is a technique of converting a variable to a different data type. But, before delving into the programming aspect, let us understand it through a more understandable example. We've all been in circumstances where we admire certain parts of a product that we saw on the internet catalog or in a store somewhere, but it wasn't entirely to our liking; we wished we could only alter certain aspects to make it the way we want it to be. Well, when it comes to dealing with digital objects, alterations are possible.
During the application development, you might need to convert the value of one data type to another for specific purposes discussed in later topics.
In Python, you can convert a variable of type a to type b using in-built methods.
Python provides the in-built float() method to convert type int into float type value.
Example:
1234 .0
You can only convert int into float data type.
Python provides the in-built int() method to convert type complex, float into int type value.
Example:
1234
You can only convert float into int data type.
Python provides the in-built complex() method to convert type int, float into complex type value.
Example:
(1234 .5678+0j) (8+0j)
Python provides the in-built tuple() method to convert type lists, set into tuple type value.
Example:
(4932, 829, 11, 3.14) (1953, 43, 193, 8134)
Python provides the in-built set() method to convert type lists, tuple into set type value.
Example:
{3.14, 11, 4932, 829} {1953, 43, 193, 8134}
Python provides the in-built list() method to convert type set, tuple into list type value.
Example:
[11, 3.14, 4932, 829] [1953, 8134, 43, 193]
Python provides the in-built str() method to perform various operations. One of them is getting the string representation of an object.
In Python, everything is an object, numerical types, lists, tuples, sets, custom implemented classes, everything.
Example:
{82, 2212, 39, 'A', 93403, 111} [11, 3.14, 4932, 829]
This chapter taught us what typecasting is, why it is required, its applications, use-cases, and several examples of converting one data type into another.