Skip to content
Home » Number to String Type Conversion in Python

Number to String Type Conversion in Python

Spread the love

This is another article on data type conversion. If you haven’t done so yet, make sure to read my previous articles as well:

String to Number Conversions

Converting String Representations of Binary, Octal and Hexadecimal Integers

Today we’ll learn how to convert numbers to strings.

Here’s the video version of this article:

Sometimes we need to use a number like a string. For example we can’t concatenate strings with numbers:

 >>> age = 32
 >>> price = 30.75
 >>> print("The " + age + "-year old woman paid $" + price + " for her hat.")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: must be str, not int 

What we have to do is cast the numbers to strings using the str function:

 >>> print("The " + str(age) + "-year old woman paid $" + str(price) + " for her hat.")
 The 32-year old woman paid $30.75 for her hat. 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply