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.