Type Casting in Python
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.
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 into Integer Data Types
- Type Casting into Float Data Types
- Type Casting into String Data Types
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 typea = 27print('data type of a: ', type(a))
#Python automatically converts b to float typeb = 3.14print('data type of b: ', type(b)) #Python automatically converts c to string typec = '3.14'print('data type of c: ', type(c)) #Python automatically converts d to float as it is a float additiond = a + bprint('value of d: ', d)print('data type of d: ', type(d)) #Python automatically converts e to float as it is a float multiplicatione = a * bprint('value of e: ', e)print('data type of e: ', type(e))
Output:
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.
Best-suited Python courses for you
Learn Python with these high-rated online courses
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 Castingfloat_val = 705.23
#Converting the float into integernum = int(float_val,2)print("The floating-point number converted into integer: ", num)
Output 1:
Example 2: Converting a string into an integer
#Explicit Type Castingstring = "11110"
#Converting the string into integernum = int(string,2)print("The string converted into integer base-2: ", num)
Output 2:
Example 3: Adding a string and an integer
string = "56"num = 44 #Converting string into integerstr_num = int(string)sum = num + str_numprint("Sum: ", sum)
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 Castingpayment = 25650TDS = payment * (0.15) #Converting integer into floatsalary = float(payment) print("Salary after tax deduction: ", salary - TDS)
Output:
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 Castingnum = 420string = str(num)print("The given number converted into string: ",string)type(string)
Output:
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
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