
Syntax: String Concatenation
Gluing two strings back-to-back with the Python string concatenation operator.
Combining Strings in Python
Previously when working with numeric values you learn about the numerous math operators in Python. In this exercise, you will be learning about the concatenation (+) operator that is used to combine strings.
The first thing you probably notice about the concatenation (+) operator is that it is the same as the addition (+) operator. Because the same operator is used for two different operations, let's see some examples of how it works:
-
If (
+) is used with two numbers, addition is performed:sum = 60 + 35 print(sum) 95 -
If (
+) is used with one number and one string, string concatenation is performed:stringVal = "hello" + 35 print(stringVal) hello35 -
If (
+) is used with two string values, string concatenation is performed:stringVal = "hello" + "old friend" print(stringVal) helloold friend
Notice in the last example that when "hello" and "old friend" were concatenated that the value saved in the variable was "helloold friend". The reason for this is that when strings are concatenated together that value that is returned is those values directly connected.
If you wanted to keep a space between "hello" and "old" There are a couple different options when using the concatenation operator. For example:
-
Option 1, add a space between the words when concatenating them:
stringVal = "hello" + " " + "old friend" print(stringVal) hello old friend -
Option 2, add a space before the
"o"in "old friend":stringVal = "hello" + " old friend" print(stringVal) hello old friend
The really important thing to remember when performing string concatenation is that the result will be exactly the way you structure it. It is best to always print the result of string concatenation so that you can confirm it is correct.
Practice: String Concatenation
Based on the above information, complete the following steps:
-
Create a variable named
first_nameand assign it a string value containing your first name. -
Create a variable named
last_nameand assign it a string value containing your last name. -
Create a variable named
full_nameand assign it the value of thefirst_namevariable concatenated with thelast_namevariable. Make sure to include a space between the first and last name.HINT*: Click here for a hint
You should see your full name output in the terminal:
> Edward Lorentz
SOLUTION*: Click here for an example solution
first_name = "Edward" last_name = "Lorentz" full_name = first_name + " " + last_name print(full_name)
When the above is completed, you are ready to move on to the next exercise!