Python String Concatenation
Concatenation is joining strings end to end into one string. The + sign joins two or more strings.
Join two names
The plus sign joins the pieces. A space string adds the gap.
first = "Ada"
last = "Lovelace"
print(first + " " + last)Join many pieces
You can chain many plus signs in one line.
a = "Py"
b = "thon"
c = " is fun"
print(a + b + c)A number will not join
Here age holds a number, not text. The plus sign refuses to join it.
age = 36
print("Age: " + age)Fix it with str()
str() turns the number into text first. Then the join works.
age = 36
print("Age: " + str(age))Fix it with commas
Commas in print() show values side by side. print() adds a space between them.
age = 36
print("Age:", age)Repeat a string
The star sign repeats a string. It works like times in maths.
print("ha" * 3)
print("-" * 10)Example
subject = "The cat"
verb = "sat"
place = "on the mat"
sentence = subject + " " + verb + " " + place + "."
print(sentence)Key points
- Concatenate: join strings end to end into one string
- Use + to join two or more strings
- Add a space string where you want a gap
- The + sign joins strings only, never a string and a number
- Use str() to turn a number into text before joining
- Use commas in print() to show text and numbers side by side
- Use * to repeat a string many times
In this example, three variables each hold part of a sentence. subject holds The cat, and verb holds sat. place holds on the mat. The long line joins all three parts with plus signs. A space string sits between each part, and a full stop ends the text. print(sentence) shows the full sentence.
Note
Joining with + makes a new string.
The pieces you joined stay unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
How do you join "Age: " with the number age, where age = 36?