Up to now, a print statement has output either a fixed piece of text or the
contents of a single variable. Concatenation lets you join those pieces
together, so that one line of output can mix fixed text with information that is
stored in variables.
Put a + between two strings and Python sticks them together into one longer
string:
print("Hello " + "world")
Hello world
A variable name can go on either side of the +. Python looks inside the
variable first, and then joins the contents to the rest:
name = "Andy"
print("Your name is " + name)
Your name is Andy
The + symbols and the variable names stay outside the speech marks.
Everything inside speech marks is treated as plain text, so
print("Your name is + name") would output the literal characters
Your name is + name.
Concatenation joins the strings exactly as they are written, with nothing inserted in between. If you want a space between two pieces, you have to write that space yourself, inside one of the strings:
first_name = "Andy"
last_name = "Colley"
print(first_name + last_name)
print(first_name + " " + last_name)
AndyColley
Andy Colley
The " " in the second print is a string that contains nothing but a single
space. It is easy to forget, and a missing space is the most common reason a
concatenated sentence comes out looking wrong.
The result of a concatenation does not have to be output straight away. You can assign it to a variable of its own and use that variable later:
first_name = "Andy"
last_name = "Colley"
full_name = first_name + " " + last_name
print(full_name)
Andy Colley
The + symbol means two different things in Python. Between two strings it
joins them together; between two numbers it adds them up. When you mix the two,
Python refuses to guess which one you meant and stops with a TypeError:
number = 7
print("You picked number " + number)
The fix is str(), which makes a string version of the value so that it can be
concatenated like any other piece of text:
number = 7
print("You picked number " + str(number))
You picked number 7
str(number) does not change what is stored in number. It only produces a
string copy for use in that one line, and the variable itself still holds the
number 7.
Run the code below. Then try removing the " " from the first print, or the
str() from the second, and run it again to see what each of them was doing.
first_name = "Andy"
last_name = "Colley"
age = 12
print(first_name + " " + last_name)
print("You are " + str(age) + " years old.")
Make sure that you check for the following things:
= for assignment.+ symbol to concatenate (join).+ symbols and the variable names are not surrounded by speech marks.