Skip to content

Module 7 · Strings — topic 5 of 22

Concatenation

Join strings with +, adjacent literals and join(). Learn the type rules, why repeated + in a loop is slow, and when f-strings or join() are better choices.

Beginner 10 min read·Lesson 86 of 306 in Python Programming

Learning objectives

  • Join strings with + and +=
  • Convert non-strings before joining
  • Build large strings efficiently with join()

Definition

Join strings with +, adjacent literals and join(). Learn the type rules, why repeated + in a loop is slow, and when f-strings or join() are better choices.

Introduction

Concatenation means joining strings end to end. "Data" + "base" produces "Database". It is the most direct way to assemble text from pieces.

Why it matters

Messages, file names, URLs and report lines are often built from several parts. Knowing the options, and which is fastest and clearest for each situation, keeps your code tidy and efficient.

Detailed explanation

Because strings are immutable, every + creates a brand-new string containing copies of both operands. For a handful of pieces this costs nothing noticeable, but it explains why join() is preferred for building text from hundreds or thousands of parts: join works out the total size once and copies each piece only once.

+ joins exactly two strings and returns a new one. Neither original is changed because strings are immutable.

+= appends to a variable: s += "!" is s = s + "!".

Both operands must be strings. "Total: " + 5 raises TypeError; use str(5) or an f-string.

+ adds no separator. Add spaces yourself or use print with commas, join() or an f-string.

Building a long string with += inside a loop creates a new string on every iteration. For many pieces, collect them in a list and call "".join(pieces) once.

For mixing text and values, f-strings (covered later in this module) are usually the clearest option.

Syntax

Python
full = first + " " + last
message += "!"
line = ", ".join(items)
  • + joins two strings.
  • += appends to an existing variable.
  • join() combines a list of strings with a separator.

Code examples

Joining with +

Python
first, last = "Neha", "Sharma"
full = first + " " + last
print(full)
full += "!"
print(full)
Output
Neha Sharma
Neha Sharma!

Converting numbers first

Python
count = 3
print("Items: " + str(count))
try:
print("Items: " + count)
except TypeError as err:
print("TypeError:", err)
Output
Items: 3
TypeError: can only concatenate str (not "int") to str

More examples

Building a file name and a CSV line

Python
student = "Asha Rao"
term = 2
file_name = student.lower().replace(" ", "_") + "_term" + str(term) + ".txt"
print(file_name)
fields = ["Asha Rao", "82", "Pune"]
line = ""
for f in fields:
line += f + ","
print(line[:-1])
print(",".join(fields))
pieces = []
for n in range(1, 6):
pieces.append(str(n * n))
print(" + ".join(pieces), "=", sum(n * n for n in range(1, 6)))
Output
asha_rao_term2.txt
Asha Rao,82,Pune
Asha Rao,82,Pune
1 + 4 + 9 + 16 + 25 = 55

Step-by-step explanation

  • The file name is built from a cleaned name, a fixed word, the converted term number and an extension.
  • The += loop adds a comma after every field, so the final slice [:-1] removes the trailing one.
  • ",".join(fields) produces the same line more simply and without the extra comma.
  • Collecting pieces in a list and joining once is the efficient pattern for many parts.

Expected output

Running “Building a file name and a CSV line” prints exactly:

TextOutput
asha_rao_term2.txt
Asha Rao,82,Pune
Asha Rao,82,Pune
1 + 4 + 9 + 16 + 25 = 55

Practical applications

  • Reports and logs are assembled from many concatenated pieces.
  • Web code builds URLs by joining a base address and a path.
  • Export features join fields with commas or tabs.

Best practices

  • Use + for two or three pieces.
  • Use join() to combine many pieces or a list.
  • Use f-strings when mixing text and values.

Common mistakes

Forgetting the separator

Avoid

first + last # "NehaSharma"

Prefer

first + " " + last

+ never adds spaces.

Repeated += for thousands of pieces

Avoid

for row in rows:
text += row + "\n"

Prefer

text = "\n".join(rows)

join() is clearer and much faster for large numbers of pieces.

Key takeaways

  • + joins strings and returns a new one.
  • Non-strings must be converted before +.
  • Use separator.join(list) for many pieces.

Try it yourself

  1. 1
    Build an email address from a first name, last name and domain using +, all in lower case.
  2. 2
    Join the words of a list with " - " between them using join().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic