Joining Strings

Concepts covered: Splitting & Joining

.join() is the opposite of split(). It combines a list of strings into a single string, inserting the separator between each element.

words = ["Python", "is", "awesome"]

sentence = " ".join(words)
print(sentence)

Output:

Python is awesome

This produces "Python is awesome". The space " " is inserted between each word.

The join() syntax

Note that .join() is called on the separator, not the list. This syntax seems backwards at first but makes sense because the separator is a string method.

Correct
  • " ".join(words)
  • ",".join(items)
  • "\n".join(lines)
Wrong
  • words.join(" ")
  • items.join(",")
  • lines.join("\n")

This is one of the most common Python mistakes. The challenge below asks you to spot it and fix it.

Common join separators

Different separators for different use cases:

items = ["apple", "banana", "cherry"]

csv = ",".join(items)
print(csv)

path = "/".join(["home", "user", "docs"])
print(path)

html = "<br>".join(items)
print(html)

multiline = "\n".join(items)
print(multiline)

Output:

apple,banana,cherry
home/user/docs
apple<br>banana<br>cherry
apple
banana
cherry

These create: "apple,banana,cherry", "home/user/docs", "apple<br>banana<br>cherry", and a multi-line string with each item on its own line.

Joining with an empty string

Joining with an empty string concatenates elements directly:

chars = ["P", "y", "t", "h", "o", "n"]

word = "".join(chars)
print(word)

Output:

Python

This produces "Python". Empty string join is useful for combining characters back into a word after processing.

About this lesson

This section is part of the Strings: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.