How to add a string to a number in Python

Let’s say you want to add a string and a number together. For example you have the string “The number of monkeys = ” and the number 17. You would like to add them together and display “The number of monkeys = 17”.

Let’s try this into the terminal:

>>> new_string = 'Number of monkeys = ' + 17
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't convert 'int' object to str implicitly

Immediately, the terminal gives us an error. This error means that we can’t perform an addition on a string and a number. The solution for this problem is to convert the number into a string so we will perform the addition on two strings which is perfectly fine.

>>> new_string = 'Number of monkeys = ' + str(17)
>>> print(new_string)
Number of monkeys = 17

Of course, you could do as shown below with the same result:

>>> s1 = 'Number of monkeys'
>>> s2 = ' = '
>>> s3 = str(17)
>>> new_string = s1 + s2 + s3
>>> print(new_string)
Number of monkeys = 17

Leave a Reply