Concatenation with +
Concatenation means joining pieces of text together. Use the + operator to combine string literals and variables:
name = "Marina"
print("Hello " + name + ", nice to meet you.")
String literals must be inside quotes. Variable names are not inside quotes—otherwise you would print the letters of the name rather than its value.
Worked examples
Build a sentence using multiple variables:
direction = "north"
country = "Wales"
print("Have you been to the " + direction + " of " + country + "?")
Mind the spaces! If you forget spaces in your strings, the result can look squashed:
day = "Saturday"
print("My birthday is on a" + day + "this year.") # missing spaces
Printing with commas
When mixing numbers with strings, prefer commas in print(). Commas automatically insert spaces and handle non-string values for you:
day = "Saturday"
print("My birthday is on a", day, "this year.")
cookies = 4
print("Munch! There's only", cookies, "cookies left.")
Practice tasks
Task 1 – Pizza toppings
Create two variables, topping1 and topping2, then print a sentence using both.
topping1 = "ham"
topping2 = "mushroom"
print("My favourite pizza is " + topping1 + " and " + topping2 + ".")
Task 2 – Stars
Create a numeric variable stars and print a sentence with it using commas.
stars = 827392012
print("I think there are", stars, "stars in the sky!")
Task 3 – Age & month
Create a numeric variable age and a string variable month. Print one sentence using both.
age = 14
month = "August"
print("I am", age, "and I was born in", month + ".")