How To Convert Data Types in Python 3

Python 3: A Guide on Converting Data Types

Introduction

Python is a programming language that is often used for system integration purposes. This language uses something called ‘data types’. These data types help classify or define a given type of data. This means that a particular data type pertains to specific values and operations that you can apply to it. Each data type is programmed and edited in a different manner. This is because each data type has a different nature. For example, you may be dealing with strings or integers.

The goal of this guide is to help familiarize you with the various data types in Python. Not only that, but we will also have an in-depth discussion about how to convert the data types into each other. By the end of this tutorial, you should know data types such as numbers, strings, tuples, and lists, and how to convert them.

Conversion of Numbers

When we talk about numbers in Python, we may be referring to one of two options. We may be dealing with either integers or floats. There may be some times when you need to convert one into the other. It is possible for you to easily convert integers into floating-point numbers and floats into integers.

  • Conversion: Integers to Floats

First, we will begin by exploring how you can convert integers into floats. The means to do this is with a command called float(). This function will convert any given integer into a float with decimals. All you have to do is place the integer inside the parentheses. For example, say you want to convert the integer 57 into a float data type. Here is how you would go about converting it:

As a result of you running this command, the integer 57 will change into the float 57.0.

Another way to do this would be to use a variable. You can denote your integer through a variable and then print the float with the above command. Let’s say you declare the variable f to be equal to 57. Here is how the conversion would go in this case:

  • Conversion: Floats to Integers

It is also possible for you to convert floats into integers. Similar to the previous command, this conversion can be done using the int() function. Just like last time, all you have to do is add the floating point number inside the parentheses following the function.

In our example, we will be converting the float 390 into an integer. To do the conversion, we would run the following command:

As a result of running this function, 390 will change into its float form: 390.8.

Likewise, you can perform the conversion with the help of variables. Not only that, but you can perform multiple conversions at the same time. Let’s assume that b is equal to 125.0 and c is equal to 390.8. Here is how you would print these floating point values:

As you can see, the integers have successfully turned into floats.

One important thing to remember during the float to integer conversion is that the function does not round up the values. This means that the decimal portion of the float is simply removed. The function will not round up a value like 390.8 to 390- it would simply remove the 0.8 units to give you an integer.

  • Conversion: Through Division

It is also possible for you to convert integers to floats through division. Dividing integers with each other may give you a quotient that is a floating point number. For example, when dividing 5 by 2, the answer you receive will be 2.5 which is a float. Take a look:

This is a special feature of Python 3. In Python 2, performing such a division would give you an integer for an answer only, like so: 5 / 2 = 2.

Conversion With Strings

Before we start talking about how to perform conversion with strings, you need to know what strings actually are. If you do not already, strings are sequences of characters. This can be a string of letters, numbers, symbols, or any other characters. You may know about strings in association with computer data. This is because computers frequently use this data type to perform their operations.

If you are dealing with user-generated data, then you will need to perform these conversions often. That is why it is handy to know how to change numbers into strings and convert strings into numbers.

  • Conversion: Numbers to Strings

You can use the str() function to convert numbers into strings. Same as before, you will place the value you want to convert within the parenthesis. This value can either be a number or a variable. To begin with, let us observe how you would convert an integer, such as 12, into a string value:

As you can see, the output shows a string value. The string value is denoted by the quotation marks.

On the other hand, you can also place variables within the function instead of integers. This is where the function becomes really useful. For example, consider that you want to track and report how many lines of code a user is writing in a given time frame. To show this information to the user, you need to print out both, the string as well as the integer values, like this:

Unfortunately, if you try to run the above code, you will receive an error like this:

concatenation error

This means that you need to convert the variable of lines into string value to be able to run the code.

Now that you placed the conversion function, you will be able to run the command successfully. You will see something like the following as your output:

Similarly, if you wish to add a float instead of an integer to a string, you have to do the same thing. Same as before, you can either add the value directly or use a variable. For instance:

If you want to make sure the value is correct, you can concatenate it with a string like this:

Since you did not receive an error, it means that the conversion was successful.

  • Conversion: Strings to Numbers

Similarly, you can convert strings into numbers as well. If your string does not have any decimal places then you are better off converting it into an integer. You can convert it into integers using the int() function.

We will continue to use our previous example from the integer conversion. Thus, consider that a user named Sammy wants to track their code writing progress on a daily basis. As a programmer, you want to present this information to the user in a creative manner. But since these values are stored as strings, you cannot apply some basic operands to them like – (subtraction). You can observe this in the following:

unsupported operand

As you can see, the operand does not work on the string values. Instead, you receive an error. To be able to work with the values, you need to convert the strings to integers using the int() function:

Here, lines_more is a variable. This variable is an integer and equal to the resultant value which, in our example, is 58.

On the other hand, you can convert the strings into floats by using the float() function if decimals are there. In this example, we will use the points the user Sammy is earning as opposed to the number of lines they are writing. The points are scored in decimal points:

While the output does not present as an error, it is still not correct. The operand + or addition worked in this case. But instead of adding the two numbers, it has simply placed the two string values next to each other.

That is why you need to convert these strings into float values first using the float() function:

As you can observe above, the two values are added together. Remember: if you try to convert a string value in decimals to an integer, you will get an error like this:

cast error

Hence, you need to convert the string data type into numbers first. Then, you can perform other operations and convert on the numeric value with ease.

Conversion to Tuples and Lists

Lists and tuples are a few other data types that you can use in Python 3. Both of these consist of a sequence of elements. The difference between the two is that where a list is mutable, a tuple is immutable. Additionally, where the elements of a list are placed within square brackets [ ], those in a tuple are put within parenthesis ( ).

  • Conversion: Lists to Tuples

First of all, let’s explore how you can convert a list into a tuple. You may need to perform this conversion if you require an immutable data type. For this purpose, you will need to use the function tuple():

As you can see, the items of the list are now in a tuple. This is shown by the parenthesis that enclose the elements.

You can also use the tuple() function with a variable that equates to the list of items:

Conveniently, you can convert any data type into a tuple. For example, here is how you would convert a string into a tuple:

Strings can be converted into tuples because they are iterable. Understandably, uniterable data types cannot be converted into tuples. Let’s say you wish to convert some integers or a float into a tuple. If you were to run the tuple() function, you will receive an error like so:

The type error shows that the integer is not iterable. That is why the conversion cannot happen. A complicated way would be to first convert the integer into a string and then into a tuple. You could do this with the following function: tuple(str(5000)). But we recommend avoiding such complications.

  • Conversion: Tuples to Lists

On the contrary, you may have to convert a tuple into a list if you require mutable data. For this purpose, you will use the list() function as such:

The presence of the square brackets indicates that the resultant output is a tuple. When writing the code to convert a tuple into a list using list(), you have to make sure you include parenthesis for the list() method as well as the print() method. However, that makes the code a bit unreadable. To make it less complicated, you can remove a pair of parentheses by using a variable instead:

Similar to tuples, you can also convert strings into lists directly:

Conclusion

This guide will help you if you are looking for ways to convert data types in Python 3. We discussed in great detail the different data types and how they can be converted into one another using built-in Python functions. Knowing these conversions will help make your programming experience much easier and more thorough.

To further explore what you can do with Python, follow our other guides:

Happy Computing!