Concatenation is something my students always find a little confusing at first.

Concatenation is about joining different pieces of information into one print function.

Example 1

To help us better understand this let’s look back at the example of how Python treats strings and integers differently. Do you remember the example below? If not run the Python editor below to see the result.

I want Python to display the equation 2+2 and then also display the answer in the same line like 2+2 = 4.

Python treats strings and integers as different objects and can’t mix the 2 unless you make it explicit what Python needs to do. Look at the 2 examples below. The first example will cause an error while the second should work.

Incorrect method

print('2+2 = ' + 2+2)

Correct method

print('2+2 = ' + str(2+2))


The first part is considered as a string because it is within quotes (print('2+2 =  . Python treats the 2+2 as alphanumeric characters. The second part is not within quotes and so is treated as an integer by Python.

Python cannot mix different types objects together implicitly (meaning without you telling it to do so). For this reason when you try to join '2+2 = ' with 2+2 Python cannot handle joining a string and an integer together.

I used the str() function to tell Python to treat the integer within the brackets as a string while still working out the result.

This way str(2+2) can be concatenated to the previous object which was a string object.


Example 2

This time I will use variables when concatenating. Hopefully your teacher has explained what a variable is in detail. if not see the footnote.

Concatenation can be very simple if we are joining a string object with another string object. This happens often in programming when joining some text with text from a variable. See the example below.

As with example 1, I will demonstrate again how to concatenate an integer object with a string object. Look at the example below and run the Python programme. One of the lines of code contains a mistake because Python cannot concatenate integer and string objects without explicitly being told to do so. Correct the mistake using the str() function.


I am the anchor.A variable is simply a name given to an object that stores information. Think of how you may label a box that contains particular items inside like old toys or winter clothes. In python, a variable will contain either a string, an integer or maybe an equation. eg  a = 10,  x = "George" or  sum1 = x + y.

Similar Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.