Type Casting in Python

Type Casting in Python

4 mins read2K Views Comment
Updated on Jul 7, 2022 11:34 IST

Through this article, you will be able to learn about type conversion or type casting in Python. We will be discussing type casting into different data types.

2022_07_Type-Casting-in-Python.jpg

When performing operations on data in Python, there are situations where we might need to convert the data type of a variable into the desired type. This is known as Type Casting or Type Conversion.

We will be covering the following sections today:

Methods of Type Casting

Type Casting is categorized into two types:

  • Implicit Type Casting – conversion of data types is done automatically by Python.
  • Explicit Type Casting – conversion of data types is done by the user.

Let’s look at how both methods work in Python:

Implicit Type Casting

The data types in Python have an order in which they are handled. When working with variables of different data types, the Python interpreter automatically converts all data types into higher-order data types. This is known as implicit type conversion. This is done to prevent data loss.

Examples of Implicit Type Casting

Example 1:

 
#Implicit Type Casting
#Python automatically converts var to integer type
a = 27
print('data type of a: ', type(a))
#Python automatically converts b to float type
b = 3.14
print('data type of b: ', type(b))
#Python automatically converts c to string type
c = '3.14'
print('data type of c: ', type(c))
#Python automatically converts d to float as it is a float addition
d = a + b
print('value of d: ', d)
print('data type of d: ', type(d))
#Python automatically converts e to float as it is a float multiplication
e = a * b
print('value of e: ', e)
print('data type of e: ', type(e))
Copy code

Output:

2022_07_typecasting-in-Python-1.jpg

What have we done here?

1.  Initialise a variable a with an integer, we see that Python implicitly converted into int data type.

2.  Initialise a variable b with a floating-point value, we see that Python implicitly converted into float data type.

3.  Initialise a variable c with text in single quotes, we see that Python implicitly converted into string data type.

4.  Then, we add variables a and b and store the sum in another variable d, we see that Python implicitly converted d to float as it has a higher order than int data type.

5.  Lastly, we multiple variables a and b and store the product in another variable e, we see that Python implicitly converted e to float again – because it has a higher order.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
3 months
– / –
2 weeks
– / –
16 weeks
β‚Ή1.7 K
3 months
– / –
– / –
β‚Ή4.24 K
2 weeks
β‚Ή3 K
3 weeks
– / –
4 months

Explicit Type Casting

In explicit type conversion, Python needs user intervention to convert variable data type into the required data type for performing a certain operation. This type casting in Python is mainly performed on the following data types:

  • int(): takes a float or string object as an argument and returns an integer-type object.
  • float(): takes int or string object as an argument and returns a float-type object.
  • str(): takes float or int object as an argument and returns a string-type object.

Examples of Explicit Type Casting

Type Casting into Integer Data Types

We can use the int() method for the conversion of a specified value into an integer object. The syntax is:

int(value, base)

Where,

  • Value: Required parameter that specifies the value that has to be converted into an integer object.
  • Base: Optional parameter that denotes the base address. If not given, the default value considered is 10 i.e., a decimal number. Other than that, the following values can be specified:

  • 2: convert a binary number into an equivalent decimal number.
  • 8: convert an octal number into an equivalent decimal number.
  • 16: convert a hexadecimal number into an equivalent decimal number.

Consider the below examples –

Example 1: Converting a float into an integer

 
#Explicit Type Casting
float_val = 705.23
#Converting the float into integer
num = int(float_val,2)
print("The floating-point number converted into integer: ", num)
Copy code

Output 1:

2022_07_image-52.jpg

Example 2: Converting a string into an integer

 
#Explicit Type Casting
string = "11110"
#Converting the string into integer
num = int(string,2)
print("The string converted into integer base-2: ", num)
Copy code

Output 2:

2022_07_image-57.jpg

Example 3: Adding a string and an integer

 
string = "56"
num = 44
#Converting string into integer
str_num = int(string)
sum = num + str_num
print("Sum: ", sum)
Copy code

Output 3:

Sum: 100

Explore Python courses

Type Casting into Float Data Types

Consider the below example to convert an integer into a floating-point number:

 
#Explicit Type Casting
payment = 25650
TDS = payment * (0.15)
#Converting integer into float
salary = float(payment)
print("Salary after tax deduction: ", salary - TDS)
Copy code

Output:

2022_07_image-55.jpg

Type Casting into String Data Types

We can use the str() method for the conversion of a specified object into a string. The syntax is:

str(object, encoding=’utf-8β€², errors=’strict’)

Where,

  • Object: Required parameter that specifies the value that has to be converted into a string object. If no value is given, the str() function returns an empty string.
  • Encoding: Optional parameter that stores the encoding of the specified object. If not given, the default value i.e., UTF-8 is considered.
  • Errors: This is the response of the str() function if the decoding fails. It is an optional parameter that stores the specified action to be performed in case of conversion/decoding failure.

Let’s consider the below example of converting an integer into a string object:

 
#Explicit Type Casting
num = 420
string = str(num)
print("The given number converted into string: ",string)
type(string)
Copy code

Output:

2022_07_image-53.jpg

Endnotes

Hope this article was helpful for you to understand type casting in Python. We learned two ways in which type casting is done in Python – implicit and explicit. We looked at each of their examples with Python codes. Python programming language is hands-down the most popular language in the tech world right now. If you seek to learn more about Python and practice Python programming, you can explore related articles here.

_______________

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio