Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconType Conversion & Type Casting in Python Explained with Examples

Type Conversion & Type Casting in Python Explained with Examples

Last updated:
19th Feb, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Type Conversion & Type Casting in Python Explained with Examples

Python has many data types, and as a programmer, you should know how to convert one data type of Python into another. Python has many built-in functions for this task. And in this simple guide, we’ll be taking a look at them to help you understand type conversions better.

After you’re through with this guide, you would know how to convert strings into integers and vice versa. So without further ado, let’s get started. 

Data Types in Python

Before we begin our discussion on type conversion in Python, let’s take a brief look at all data types present in this language:

Integers

Integer values can be as long as you want. Like in mathematics, integers in Python are digits too. But you can’t have indefinitely long integers unless you have a supercomputer. Python treats any number without a prefix as an integer. These numbers include decimal digits too.

Floating Point Numbers

Floats in Python are numbers that are written with a decimal point for separating the fractional digits and the integer. Some examples of floating-point numbers are 4.3, 9.18, etc. You can add ‘e’ for the scientific notation in Python as well. 

Complex Numbers

Complex numbers in Python follow this format: (the real part + the imaginary part). Some examples of complex numbers are (3+2i), (8-2x), etc. 

Strings

Strings can be any particular set of characters in Python. They are referred to as str. You can write them by using quotation marks. You can use single quotes as well as double quotes for writing strings in Python. Strings can be any characters placed in quotation marks such as ’91’, “hello”, etc. 

Just like integers, there is no limit to character length in strings. Strings are of various types, such as triple-quoted strings, raw strings, and many others. However, if we would start discussing strings and their kinds, this article will go too long. 

Boolean Data Type

The final data type we have left to discuss is the Boolean data type. Boolean data can have one of two values, which are true and false. Boolean values are quite essential in Python for many reasons. You can use Boolean values to determine the truthiness of objects and values. 

Read: Python Developer Salary in India 2020

As you’ll learn more about logical operators in Python, you will have to deal with Boolean objects and values. 

So these were all data types present in Python. Learn more about the data types in Python. Apart from these data types, Python also has many built-in functions, which help it in performing a variety of tasks. We’ll need to use a few built-in functions to implement type conversion as well. Checkout our data science programs to learn about various types of conversions.

Now that we’ve discussed data types, we can move onto type conversion. 

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

 

Different Kinds of Type Conversions in Python

There are two kinds of type conversions in Python. They are the following:

Implicit

In this case, Python converts a data type into another type automatically. You, the user, don’t have to get involved in this process. Here is an example of implicit conversion of integer to float in Python:

num_int = 18

num_flo = 1.8

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 of the above code would be the following:

datatype of num_int: <class ‘int’>

datatype of num_flo: <class ‘float’>

Value of num_new: 19.8

datatype of num_new: <class ‘float’>

As you can see, we only had to add num_flo and num_int along with num_new to get the desired output. We converted the integer 18 into a float 19.8 through a few lines of code. The vital thing to note here is that Python turned the integer into float automatically.

Explore our Popular Data Science Courses

Explicit

In the case of explicit type conversion, we use functions for converting purposes. Remember the built-in functions we mentioned before? They will come in handy in this section. Another name for explicit type conversions is typecasting. It has this name because you, the user, cast the data type of the concerned object. 

There are some type conversion functions you should be familiar with to perform typecasting in Python. Int(a,base) is a popular function as it can convert any data type into an integer. float() can turn any data type into a floating-point number. oct() converts integers to octal strings, and hex() converts integers to hexadecimal strings. 

Here is an example of type conversion using oct():

c = oct(80)

print (“Output : “,end=””)

print (c)

And the output would be:

Output : 0o120

 

When working with these functions, remember that the syntax for such conversion should be:

(desired_datatype)(expression)

There are many kinds of type conversions you can perform in Python. However, there are two kinds of them, which you’ll be performing the most. Converting strings into integers and vice versa can be a great starting point. So let’s discuss each of those type conversions separately for a better understanding of this topic:

Read: Python Developer Project Ideas & Topics

Converting String to int Python 

You can convert a string to int Python through the int() function. It gives you a decimal integer with just a click. It assumes that the expression you’ve entered is a decimal integer, but if it’s not, it will return a ValueError. And we don’t want that. You can mention the number system you require by giving the value a base to avoid this problem. 

So, if you’re converting a string to int in Python you can do this:

int(“5”)

Or, you can add a base for different kinds of strings:

int(“5” , base=10)

Now let’s discuss the reverse of this conversion, i.e. when you need to convert an integer into a string.

Converting int to String Python

You can use the str() function for converting integers into strings. Just follow the syntax we mentioned before:

str(5)

Strings can convert integers into decimal expressions if you use a binary literal. However, just like with the int function, if you require, you can add more information for different conversions. You can get octal, binary, and even hexadecimal results with this function. 

After a little practice, you can perform more complex tasks with type conversion as well. Here’s an 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 output of the above code would be this:

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 a lot of fun. Feel free to experiment with type conversions and expand your knowledge base. 

Top Data Science Skills to Learn

Conclusion

We hope you learned a lot from this article. Performing type conversions is one of the many things you can do with Python’s functions. 

If you are reading this article, most likely you have ambitions towards becoming a Python developer. If you’re interested to learn python & want to get your hands dirty on various tools and libraries, check out IIIT-B’s PG Diploma in Data Science.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1In coding, how are explicit conversions different from implicit conversions?

An implicit type conversion is a type conversion that is defined by the user and compels an expression to be of a certain type. When several data types are combined together in an expression, the compiler performs an implicit type conversion. Explicit conversion, also known as casting, is when we explicitly convert from one data type to another by executing the appropriate function for the data type we wish to convert to. Without the assistance of the programmer, an implicit type conversion is accomplished.

2How is type casting different from type conversion?

The destination data type must be smaller than the source data type when type casting one data type to another. However, the source data needs to be smaller than the destination data type when converting one data type to another. A programmer must manually type cast one kind of data into another type. Converting one data type to another does not involve any programmer intervention because the compiler automatically compiles it during program execution. There is a chance that data or information will be lost during type casting. When converting a small data type to a large data type, data is unlikely to be lost.

3Which is more efficient in Python- tuples or lists?

A tuple is a comma-separated collection of Python objects and because of its static nature, the tuple is quicker than the list. Tuples are also more efficient in terms of memory than lists. When it comes to time efficiency, tuples have a minor edge over lists, particularly when it comes to looking up to a value. If you have data that isn't supposed to be altered in the first place, a tuple data type should be preferred over a list. We may make a list of tuples, which means that the members of the tuple can be wrapped in a list and therefore follow the same characteristics as a Python list. Because Python Tuples take up less space, constructing a list of tuples is more practical.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905292
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions &#038; Answers [For Freshers &#038; Experienced]
20938
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5069
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5181
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17656
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types &#038; Techniques
10807
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80815
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories &#038; Types [With Examples]
139162
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon