Python Principles

How to convert an integer to a string

To convert an integer to a string, use the str() built-in function.

The function takes an integer (or other type) as its input and produces a string as its output. Here are some examples.


Here's one example:

>>> str(123)

If you have a number in a variable, you can convert it like this:

>>> number = 999
>>> number_as_string = str(number)
>>> number_as_string

Concatenating strings and integers

Sometimes you need to construct a string that contains a number from another variable. Here is an example:

>>> week = 33
>>> greeting = "it is week " + str(week)
>>> greeting
'it is week 33'

Avoiding conversions

Usually, people need the str() function when they want to concatenate a number and a string. This happens right before printing. For example:

>>> name = "Bob"
>>> age = 33
>>> print(name + " is " + str(age) + " years old")
Bob is 33 years old

However it is much cleaner to use the .format() method on strings instead:

>>> print("{name} is {age} years old".format(name=name, age=age))
Bob is 33 years old

It is even cleaner to use f-strings, a new feature in Python 3:

>>> print(f"{name} is {age} years old")
Bob is 33 years old

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!