Sub topic 7
Combining strings with str.join
str.join is the standard way to turn a collection of strings into one string. This chapter covers how it works, what it accepts, and where it surprises people. It assumes you can run Python code, work with lists and tuples, call methods and read their return values, and write a basic for loop or generator expression.
The shape of a join call
join is a method of the separator, not of the list. You write the separator first, then pass the items:
words = ["red", "green", "blue"]
print(", ".join(words)) # red, green, blue
print("".join(words)) # redgreenblue
print("-".join("abc")) # a-b-cThe separator goes between items only. The result has no leading or trailing separator, which is the main reason join is more convenient than building the string by hand.
Like every string method, join returns a new string and leaves its inputs unchanged. Strings are immutable, so you must use or store the result:
words = ["red", "green", "blue"]
words_text = ", ".join(words)
print(words) # ['red', 'green', 'blue']
print(words_text) # red, green, blueWhy the method lives on the separator
Newcomers often try words.join(", "). That fails because lists have no join method:
words = ["red", "green", "blue"]
try:
words.join(", ")
except AttributeError as error:
print(error) # 'list' object has no attribute 'join'Python puts join on str because the operation produces a string and needs a string to act as the glue. If join were a list method, tuples, sets, generators and every other iterable would each need their own copy. As a str method, it works with anything you can loop over, as long as the items are strings.
What join accepts
The argument can be any iterable that yields strings. Lists are the common case, but these all work:
# A tuple
print("/".join(("usr", "local", "bin"))) # usr/local/bin
# A generator expression
words = ["red", "green", "blue"]
print(" ".join(w.upper() for w in words)) # RED GREEN BLUE
# A map object
print(",".join(map(str.strip, [" a ", "b ", " c"]))) # a,b,c
# A dictionary: iterating a dict yields its keys
scores = {"x": 1, "y": 2}
print("+".join(scores)) # x+yTwo details are worth knowing.
- A string is an iterable of one-character strings.
" ".join("hello")gives'h e l l o'. This is occasionally useful, as in the"-".join("abc")example above. It is more often a bug, when you meant to pass a list and passed a single string. - A set has no reliable order.
", ".join({"a", "b", "c"})produces the items in whatever order the set yields them, and that order can change between runs for strings. If you need a stable result, joinsorted(the_set).
The separator can be any string, including a multi-character one or an empty one:
steps = ["read", "parse", "write"]
print(" -> ".join(steps)) # read -> parse -> write
print("\n".join(steps))
# read
# parse
# writeThe last example shows a common use. "\n".join(lines) builds multi-line text, and it adds no newline after the last line. If a file or protocol expects a final newline, add it yourself: "\n".join(lines) + "\n".
Edge cases
Empty and tiny inputs behave consistently, and it helps to know them in advance.
| Expression | Result | Why |
|---|---|---|
| `",".join([])` | `''` | No items, so there is nothing to place a separator between. |
| `",".join(["only"])` | `'only'` | One item has no neighbours, so no separator appears. |
| `",".join(["", ""])` | `','` | Two empty strings still have one gap between them. |
| `",".join(["a", "", "b"])` | `'a,,b'` | Empty items are kept, and each gap gets a separator. |
| `"".join(["a", "b"])` | `'ab'` | An empty separator concatenates the items directly. |
You can check them yourself:
print(repr(",".join([]))) # ''
print(repr(",".join(["only"]))) # 'only'
print(repr(",".join(["", ""]))) # ','
print(repr(",".join(["a", "", "b"]))) # 'a,,b'
print(repr("".join(["a", "b"]))) # 'ab'Joining an empty iterable returns an empty string rather than raising an error. That lets you write ", ".join(names) without first checking whether names is empty. The behavior mirrors the empty-field results of split from the earlier chapters. ",".join(["a", "", "b"]) gives back text that split(",") turns into the same three items.
The items must be strings
join does not convert anything for you. If one item is not a str, it raises TypeError and names the position of the first offender:
try:
print(",".join(["a", "b", 3]))
except TypeError as error:
print(error) # sequence item 2: expected str instance, int foundThe position in the message is a zero-based index into the iterable, so "sequence item 2" is the third item. The fix is to convert items before joining. That is the topic of the next chapter, so this chapter only asks you to recognize the error when you see it.
join also does not mix text and bytes. The bytes type has its own join method, which works on bytes items with a bytes separator:
print(b",".join([b"a", b"b"])) # b'a,b'
try:
",".join([b"a", b"b"])
except TypeError as error:
print(error) # sequence item 0: expected str instance, bytes foundA worked example: building a readable list
Suppose you want to turn a list of names into an English phrase such as "Ada, Grace, and Alan". join handles the commas. You handle the final "and" separately, because it is a different separator from the rest.
def human_list(items):
items = list(items)
if not items:
return ""
if len(items) == 1:
return items[0]
if len(items) == 2:
return " and ".join(items)
return ", ".join(items[:-1]) + ", and " + items[-1]
print(repr(human_list([]))) # ''
print(human_list(["Ada"])) # Ada
print(human_list(["Ada", "Grace"])) # Ada and Grace
print(human_list(["Ada", "Grace", "Alan"])) # Ada, Grace, and AlanThe function starts with list(items) so it also accepts generators and other iterables, which cannot be sliced or measured with len directly. It handles the empty, one-item and two-item cases separately because each uses different punctuation. Only the three-or-more case needs two separators.
Join and split as a pair
split and join are inverses when the data is simple. Splitting on a separator and joining with the same separator returns the original text:
text = "a,b,,c"
parts = text.split(",")
print(parts) # ['a', 'b', '', 'c']
print(",".join(parts)) # a,b,,c
print(",".join(parts) == text) # TrueThis pairing is useful for transformations. You split, change some of the parts, and join again:
path = "usr/local/bin"
parts = path.split("/")
parts[0] = "opt"
print("/".join(parts)) # opt/local/binThe round trip is not always exact. " hello world ".split() followed by " ".join(...) gives 'hello world', which collapses the extra whitespace and so no longer matches the original. A later chapter looks at when round trips hold and when they lose information.
Common mistakes
- Calling join on the list. Use
separator.join(items), notitems.join(separator). - Passing a string when you meant a list.
", ".join("red")returns'r, e, d', with no error to warn you. - Forgetting to use the result.
joinreturns a new string. A bare", ".join(words)on its own line does nothing useful. - Joining non-strings. Convert items first, or you get
TypeError. - Relying on set or unordered input. Sort first when the output order matters.
- Mixing
+andjoinwithout parentheses. The method call binds tighter than+, so"Items: " + ", ".join(items)works as expected. If you put a conditional expression in the same line, add parentheses so the result is easy to read.
Joining generated data
Because join accepts any iterable, you can feed it a generator expression and skip the intermediate list in your own code. Here is a compact example that formats rows of a small table:
rows = [("apple", 3), ("pear", 12), ("fig", 7)]
lines = (f"{name:<8}{count:>3}" for name, count in rows)
print("\n".join(lines))
# apple 3
# pear 12
# fig 7The f-string already turns the integer into text, so every item that reaches join is a string. CPython's join collects the items into a sequence before it builds the result, so passing a generator does not save memory over passing a list. Use whichever form reads better.
Exercise
What does "-".join(["a", "", "b"]) return, and what does "-".join([]) return?
Show answer
The first call returns 'a--b', because the empty string in the middle is kept and each of the two gaps gets a separator. The second call returns '', an empty string, because there are no items to place a separator between and join does not raise an error for an empty iterable.
Exercise
A teammate wrote result = ", ".join(["id", 7, "name"]) and got TypeError: sequence item 1: expected str instance, int found. What does "item 1" refer to, and what is the shortest change that fixes the code?
Show answer
"Item 1" is the item at zero-based index 1, which is the integer 7. The shortest fix is to convert the items to strings before joining, for example ", ".join(str(x) for x in ["id", 7, "name"]), or ", ".join(map(str, ["id", 7, "name"])). Both produce 'id, 7, name'.
Exercise
Why is the method called as ", ".join(words) rather than words.join(", "), and what does " ".join("hi") return?
Show answer
join belongs to str so that it works with any iterable of strings (lists, tuples, generators, dictionary keys) without each type needing its own copy of the method. " ".join("hi") returns 'h i', because a string is an iterable of one-character strings and those characters are joined with the separator.