Documenting a Journey to Data Science!

DataScience Ville Logo
Search
Close this search box.

How to Convert Python Data Types Using Functions (Str, int, float)

There are several data types in Python. Among these, the strings, integers, and floats are the basic three you’ll first need to work with.

And knowing how to convert between these data types is very necessary while coding. But, if you’re a total noob to programming, you might be wondering: “what are String, Integers, and Floats?”

Let’s take a second to consider these:

What is a String in Python?

A string is basically anything you write within quotes in Python. This ranges from a simple phrase like “Hello world” to the use of numbers like “5”

Check out this post for the different ways of writing strings:

What is an Integer in Python?

An integer is a numeric data type in Python. It’s simply a whole number (either positive or negative). But wait, above, we said strings can be numbers, didn’t we? Well, as long as it isn’t within quotation marks, it’s an integer.

What is a Float in Python?

A float, like an integer, is a numeric data type. But this is how we refer to decimals.

Converting Data Types in Python

Now, how do we convert from one type to another?

First, why would a programmer want to make such conversions?

After all, both integers and floats are numeric data types. So, won’t a code like this work?

Well, it’s going to work fine as seen below:

a screenshot showing implicit conversion of python data types.

That’s because Python is doing the conversion for you behind the scenes (This is called Implicit Conversion).

But in scenarios where you need to calculate a string and an integer, your code will return an error.

And scenarios like that happen pretty often. Not to worry, in such situations, we make use of the following Python’s built-in functions:

str (for converting integers or floats to strings)

For a scenario, where you need to print an integer together with a string, you’ll need to use the “str” function.

EXAMPLE:

int (for converting strings or floats to integers)

For the scenario described above where you need to calculate a string and an integer, you’ll need to use the “int” function.

EXAMPLE:

float (for converting strings or integers to floats)

EXAMPLE:

Concluding Words…

When converting from one data type to another, you need to first identify what you want.

Do you want to calculate an integer and a string? Or do you want to print out a float as a string? Once you know what you want, it’s just a matter of using the conversion function that best works in that scenario.

That’s it for this post. Thanks for reading and Till next time!

Popular Tags

AUTHOR OF BLOG

Categories

Categories

Related Posts

 Get Insightful News on Data-related Topics

SUBSCRIBE FOR REGULAR UPDATES

Discover more from Kester R. on a wider range of topics here on: