How to Perform Type Casting And Type Conversion In Python

How to Perform Type Casting And Type Conversion In Python
How to Perform Type Casting And Type Conversion In Python

In this article, you will learn about how to perform Type Casting and Type Conversion in Python.

What is Type Casting In Python?

Type Casting in Python can be defined as the combination of Implicit and Explicit functions. Moreover, type Casting converts the variable data type into the required data type to implement the operation required by users. 

It is converting one data type to another data type by using some unique function keywords. Some places where we want to convert the data type. For instance, if we want to add two numbers in which one of the existing values of a variable is an integer and the second is a string.

Diagram

Description automatically generated

I=int(x,2)——–this will convert the number stored into the string into a base two-digit.

F=float(x)——-this will convert the string into a floating point digit.

Python expels the loss of data in Implicit Type Conversion. Explicit Type Conversion, also called Type Casting, is in which the data types of objects are converted by using predefined functions by the user.

Graphical user interface

Description automatically generated with low confidence

Python has an advantage by which it converts one data type to another data type. This process does not need any user involvement Python promotes the conversion of lower data types; for example, integer to higher data type says float to avoid data loss. This type of conversion or typecasting is named Upcasting. As explained here, we use explicit and implicit functions.

Also Read: Best Programming Languages to learn in 2021

These are some of the built-in functions that are used in typecasting:

  • Int(): convert any type variable to the integer type.
  • Float(): convert any data type of variable to the float type.
  • Complex (): convert any data type variable to the complex type.
  • Bool(): used to convert any type variable to the bool type.
  • Str(): convert any variable to the string type.

Here, data loss may occur because we make or convert the object to a specific data type.

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one type of data to another data type. This process doesn’t require any user involvement.

num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

The output for the above program is:

datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>

In the above program, we added two variables, num_int and num_flo, storing the value in num_new.

The study of three objectives that are different is done here.

In the output, we can observe that the data type of num_int is an integer, whereas the data type of num_flo is a float.

Also, we can see the num_new has a float data type because this programming language always converts smaller data types to larger data types to avoid data loss.

Explicit Type Conversion

In Explicit Type Conversion, the user can convert the data type of an object to desired data type. Here, the predefined functions like int(), float(), str(), etc are used to perform explicit type conversion.

This type of conversion is also called typecasting since here, the user casts (changes) the data type of the objects.

Syntax:

<required_datatype>(expression)
pi = 3.14 # float number
print(type(pi))
# Output class 'float'
# converting float integer
num = int(pi)
print("Integer number:", num)
# Output 3
print(type(num))
# Output class 'int'

Bool Type Conversion

We use the built-in function bool() to change values of other types to bool types as we know that this function returns two values: either True or False.

Here, we can change any value to a bool type, and the output for all values will be True, Except 0, which is False.

If you convert an empty string to a boolean, it turns to boolean False. The bool for values True is 1, and False is 0. Every non-zero value is treated as True.

Casting An Integer to Boolean Type

num1 = 10
num2 = 0
print(type(num1)) # class 'int'
# Convert into to bool
b1 = bool(num1)
b2 = bool(num2)
print(b1)
# Output True
print(b2)
# Output False
print(type(b1))
# class 'bool'

String type conversion

We use the built-in function str() in str type conversion, which converts variables of other types to a string type. This function returns the string type of object (value).

Casting int to str type

num = 15
print(type(num)) # class 'int'
# converting int to str type
s1 = str(num)
print(s1)
# Output '15'
print(type(s1))
# Output class 'str'

Casting of float type to str type

num = 75.35
print(type(num)) # class 'float'
# converting float to str type
s1 = str(num)
print(s1)
# Output '75.35'
print(type(s1))
# Output class 'str'

Casting of complex type to str  type

complex_num = 15 + 5j
print(type(complex_num)) # class 'complex'
# converting complex to str type
s1 = str(complex_num)
print(s1)
# Output '(15+5j)'
print(type(s1))
# class 'str'

Casting from bool type to str type

b1 = True
b2 = False
print(type(b1)) # class 'bool'
# converting bool to str type
s1 = str(b1)
s2 = str(b2)
print(s1)
# Output 'True'
print(s2)
# Output 'False'
print(type(s1)) # class 'str'

Converting int to String Python

Here we can use the str() function to convert integers into strings. Do follow the syntax we mentioned before:

str(5)

Strings can be converted from integers to decimal expressions when a binary literal is used. However, just like with the int function, you can add more information for different methods if you require. You can get octal, binary, and even hexadecimal results by using or with the help of this function.

In addition, after doing some programs, one can perform more complex tasks with type conversion as well.

Example of Adding a String With An Integer through Typecasting

num_int = 256
num_str = “64”
print(“Data type of num_int:”,type(num_int))
print(“Data type of num_str before Type Casting:”,type(num_str))
num_str = int(num_str)
print(“Data type of num_str after Type Casting:”,type(num_str))
num_sum = num_int + num_str
print(“Sum of num_int and num_str:”,num_sum)
print(“Data type of the sum:”,type(num_sum))

The above will give the output as follows:

Data type of num_int: <class ‘int’>
Data type of num_str before Type Casting: <class ‘str’>
Data type of num_str after Type Casting: <class ‘int’>
Sum of num_int and num_str: 320
Data type of the sum: <class ‘int’>

As you can see, it’s very easy. Just try to experiment with type conversions, typecasting, and improve your knowledge base.

Moreover, when typecasting one data type to another, the destination data type must be less than the source data type. Furthermore, the source data needs to be smaller than the destination data type when converting one data type to another. A programmer has to typecast one kind of data into another type manually.

Also, converting one data type to another does not require interpretation because the compiler automatically compiles it during program execution. There are some chances that the data or information will be lost during typecasting. Also, there can be a data loss when converting a lesser data type to a large data type.

Thus, as stated above, we can say that it depends on whether to use type conversion or typecasting, and one cannot say that either of them is easy. Because it purely depends on the need of the programmer and requirements concerning data.

LEAVE A REPLY

Please enter your comment!
Please enter your name here