TNS
VOXPOP
Do You Resent AI?
If you’re a developer, do you resent generative AI’s ability to write code?
Yes, because I spent a lot of time learning how to code.
0%
Yes, because I fear that employers will replace me and/or my peers with it.
0%
Yes, because too much investment is going to AI at the expense of other needs.
0%
No, because it makes too many programming mistakes.
0%
No, because it can’t replace what I do.
0%
No, because it is a tool that will help me be more productive.
0%
No, I am a highly evolved being and resent nothing.
0%
I don’t think much about AI.
0%
Python / Software Development

How and Why You Should Use Type Casting in Python

This tutorial introduces you to type casting in Python. Type casting is the method to convert the Python variable datatype into a certain data type in order to perform the required operation by users.
May 17th, 2024 8:11am by
Featued image for: How and Why You Should Use Type Casting in Python
Feature image via Unsplash+.

Type Casting is the process of converting an object from one data type to another. Data types are data items that have been classified or categorized into things like numbers, integers, strings, and so on.

We can classify 1 as an integer, 1.3 as a (float) number, and one as a string like this:

  • a=10 – an integer (or int)
  • b=10.5 – a float number
  • c=”10″ – a string

At times, you might want to convert those numbers. For example, you might create an application with a function that requires only integers, so you might need to cover 10.5 to 10. Or you might need to convert a string into an integer, like “10” to 10.

Here’s a simple example of that.


Let’s take a look at what we have above. If we were to attempt to add string + number, the app would throw an error because you can’t add a string to a number. It’s not mathematically possible. That would be like adding “Duck” to 10 and we all know that Duck + 10 = You Can’t Do That!.

To get around that issue, we use type casting to convert the string to a number with type casting. To convert the string to a number, we use:


What we’ve done is use the int() function for explicit conversion.

Before we go much further, let’s talk about the two types of conversion in Python, which are implicit and explicit type casting.

Implicit Casting in Python

This type of casting is when a compiler or interpreter automatically converts an object of one type to another. Python, however, is a strongly typed language, which means such automatic conversions are not possible. The Python interpreter simply will not automatically convert a string to a number. That’s on you.

However, Python will automatically cast int to float. Here’s a simple example of implicit type casting:


If you were to run the above, the results would be 20.5. Essentially, Python has converted the integer 10 to a float 10.0.

That’s implicit casting. You don’t have to do anything because the object with the lesser byte size is upgraded to an object of a greater byte size during the operation (in the example above, a+b).

There’s another handy trick with implicit type casting. Consider that, in Python, True is a boolean object and equals 1 (where False equals 0). So what if we were to set a to True, b to 10, and add them together like this:


What do you think the result would be? Well, since a = True (which is 1) and b = 10, a+b would equal 11.

If, on the other hand, you set a to False, the result would be, you guessed it, 10.

Explicit Casting in Python

On the other hand, explicit casting in Python is done within the code and handled via the int() and float() functions.

Let’s say you have a program that takes a salary and adds a bonus, printing the results as an integer (whole number). For that, you use the float() function like this:


As you can see, we’ve defined new_salary as a floating point conversion of salary (from 250000 to 250000.0) and then added it to bonus, which is defined as salary multiplied by 0.50. The output of the above code would be:

Salary converted to a floating-point number:  250000.0
Salary after adding a bonus:  375000.0

There are other types of explicit type casting you can do in Python. Here are some examples.

You can convert a binary string to an integer like this:


The above would convert the base 2 binary “1100100” to the integer 100. You could also convert to base 8 or 16.

Convert an octal number (base 8) like this:


Since 0o144 in octal is 100, a would equal 100.

In hex, 0x64 = 100, so it would look like this:


The result? 100.

Let’s make sure we know the class of our numbers (to avoid confusion). Take, for example, the following:


The output of the above would be:

100.1
<class ‘int’>
<class ‘float’>
<class ‘float’>

We can also convert an int to a string. This is done like so:


We’ve essentially converted the number 100 to the string 100 using explicit type casting. Of course, you could simplify this even more by defining number = “100” but there may be times when you can’t do that in defining your variables, but at some point in the code need to explicitly type cast from int to string.

If you’re using a version of Python 3.6 or newer, there’s also the f-string function, which can convert int to string and do it more quickly than the str() function can. Using f-string looks like this:


When you use f'{}’, it converts anything within the braces from int to string.

Let me show you a more useful example of f-strings. We’re going to import the datetime function, define a few variables, and then print with the f-string function. That code looks like this:


The output of the above would be:

My name is Jack, my age next year will be 51, and my anniversary is Wednesday, July, 19, 2006.

Note that %A, %B, %d, %Y is the formatting type for the datetime.date function, such that it prints out Day of the week, Month, Day, and Year.

It is also possible to convert sequence types, such as a string or tuple into a list. Similarly, you can convert a string or list into a tuple.

For example, you have the string:


We can convert that string to a list using the list() function, like so:


The full code (including a print statement) looks like this:


The output would be:

[‘N’, ‘e’, ‘w’, ‘ ‘, ‘S’, ‘t’, ‘a’, ‘c’, ‘k’]

Huzzah, we’ve converted a string to a list.

And that’s the gist of type casting in Python. This is an important feature that you will eventually want to lean into so that you can be certain you’re always dealing with the necessary types of types to keep your applications running smoothly.

Group Created with Sketch.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.