Sub topic 7
Combining strings with str.join
This chapter assumes you can run Python code and know how lists, tuples and strings behave. It also assumes you can call a method and read its return value, and that you have seen a for loop. Here you will learn how str.join builds one string from many.
The basic call
join is a string method. You call it on the separator, and you pass the pieces as the argument. It returns one new string with the separator placed between neighbouring pieces.
words = ["red", "green", "blue"]
print(", ".join(words)) # red, green, blue
print("".join(words)) # redgreenblue
print("-".join("abc")) # a-b-cStrings are immutable, so join never changes words or the separator. It builds a new string, and you must use the return value.
Why the separator owns the method
It may look odd that the call is ", ".join(words) and not words.join(", "). The reason is that join accepts any iterable of strings, not just lists. If join lived on the list, tuples, sets, generators and dictionaries would each need their own copy. Putting it on str means one method serves all of them.
print("/".join(("usr", "local", "bin"))) # usr/local/bin
print(" ".join({"a": 1, "b": 2})) # a b
print(" ".join(w.upper() for w in ["red", "green", "blue"])) # RED GREEN BLUEA dictionary yields its keys when you iterate over it, so only the keys are joined. A generator expression works because join reads the items one at a time.
A string is an iterable too
A string is an iterable of one-character strings. If you pass a string to join, it joins the characters:
print("|".join("hi")) # h|iThis is a common source of surprises. If you meant to join a list but passed a single string by mistake, you get no error, just separators between letters.
Edge cases
The separator appears only between items. It never appears at the start or end, so you do not need to strip a trailing separator. Two small inputs are worth knowing:
print(repr(", ".join([]))) # ''
print(repr(", ".join(["solo"]))) # 'solo'An empty iterable gives an empty string. A single item comes back without any separator. Both results are what you want in most programs, so you rarely need a special case for them.
An empty separator is also valid. "".join(parts) glues the pieces together directly.
Items must be strings
Every item must be a str. If one is an integer, None or anything else, join raises TypeError.
try:
", ".join(["a", 2])
except TypeError as error:
print(error) # sequence item 1: expected str instance, int foundThe message names the position of the first bad item, which helps when the data is long. The next chapter shows how to convert items before joining.
Joining after splitting
split and join are close to opposites. You can split a string, change the pieces, and join them back with a new separator:
path = "usr/local/bin"
parts = path.split("/")
print(".".join(parts)) # usr.local.binYou can also clean the pieces on the way. Here each word is capitalized before the join:
title = "the quick brown fox"
print(" ".join(word.capitalize() for word in title.split())) # The Quick Brown FoxThis pattern of split, transform and join is common in text processing.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `words.join(", ")` | `AttributeError`, because lists have no `join` | Call it on the separator: `", ".join(words)` |
| Ignoring the return value | The original data is unchanged and the joined text is lost | Assign the result or print it |
| Passing a string instead of a list | Separators appear between characters | Pass a list or tuple of strings |
| Passing numbers | `TypeError` | Convert each item to `str` first |
Exercise
What does "-".join(["ab", "cd"]) return, and what does "-".join("ab") return? Explain the difference.
Show answer
The first returns 'ab-cd', because the list has two string items and the separator goes between them. The second returns 'a-b', because a string is an iterable of its characters, so join treats 'a' and 'b' as the two items.