String Concatenation
Concatenation means joining strings together to make one string.
Example
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
# outputs: Ada Lovelace
Rules
- Use
+to join strings. - Add spaces yourself:
"Hello" + " " + "world". - Convert non-strings with
str()or use f-strings.
More Examples
Print a message with a count:
When concatenating a string with a number, you need to convert the number to a string using the str() function. If you don't, you will get a type error.
count = 3
print("You have " + str(count) + " new messages")
Print a dynamic border with end and beginning characters:
border_width = 10
# subtract 2 for the "-" characters to account for the beginning and ending "+" characters os that they still add up to the border_width
print("+" * "-" * (border_width - 2) + "+")
# outputs: +----------+