Converting Integer to String in Python

To convert an integer to a string, Python uses the str() function. This function takes one argument (e.g. integer) and converts it into a string. This value can be displayed as an output or merged with other string values.

Look at this example:

It’s the same as:

Printing the result

If you want to just display a number, you don’t have explicitly convert an integer to string, the print function will do it for you.

This works:

But this also works:

Python offers the type function to check the type of variable.

This will display the following results:

<class 'int'>
<class 'str'>
<class 'str'>

Joining strings and integers

The problem starts when you need to join variables with other string. Now, you can’t use the int variable without explicit conversion.

The following code won’t work:

But after converting the value to string it works flawlessly:

You can also convert the value inside the print function:

The format function

The str function is useful when you want to convert one, or two values, but when you have more of them you may want to use the format function.

Here’s how it works:

This code will generate the following message:

John is 45 years old and has 4 kids.

There is a different version of this code. Instead of using indexes, you can specify names.

This code will generate the same result as the code before.