Sub topic 8
Joining Numbers and Other Non-String Items
This chapter assumes you know str.join from the previous chapter. You should be comfortable with lists, tuples, for loops and generator expressions. Here you will learn why join rejects numbers, how to convert items before joining, and how to handle values such as None, floats, bytes and nested lists.
Why join insists on strings
str.join glues together text. It does not guess how a number, a None or an object should look as text. Several valid renderings exist: 2.0 could appear as 2.0, 2 or 2.00. Python makes you choose.
Passing a non-string item raises a TypeError:
numbers = [1, 2, 3]
try:
print(",".join(numbers))
except TypeError as error:
print(error)
try:
print(",".join(["a", 2, "c"]))
except TypeError as error:
print(error)The output is:
sequence item 0: expected str instance, int found
sequence item 1: expected str instance, int foundThe message names the position of the first bad item and its type. Read it as a pointer to the item to fix. Only the first offending item is reported, so fixing it may reveal another error.
Other languages convert silently here. For example, JavaScript's [1, 2, 3].join(",") works. Python's strictness prevents bugs where None or a nested list sneaks into output as text.
Converting items with str()
The standard fix is to convert each item to a string before joining. You have two common ways to do it.
numbers = [1, 2, 3]
print(",".join(str(n) for n in numbers)) # 1,2,3
print(",".join(map(str, numbers))) # 1,2,3
print(",".join([str(n) for n in numbers])) # 1,2,3All three give the same result. Choose by readability:
map(str, items)is the shortest when you only call one function.- A generator expression reads best when you need more than a function call, such as a condition or a format specification.
- A list comprehension builds the full list first.
joinneeds to know the total length before it builds the result, so it collects any generator into a list internally. A list comprehension therefore costs about the same.
str() leaves strings unchanged, so it is safe on mixed lists:
mixed = ["id", 42, 3.5, True]
print("-".join(map(str, mixed))) # id-42-3.5-TrueNote that True becomes 'True', with a capital T, because that is what str(True) returns.
Controlling how numbers look
str() gives the default text form. When you need control, use an f-string with a format specification instead:
values = [1.5, 2, 3.14159]
print(", ".join(str(v) for v in values)) # 1.5, 2, 3.14159
print(", ".join(f"{v:.2f}" for v in values)) # 1.50, 2.00, 3.14
print(" ".join(f"{n:03d}" for n in [7, 42, 105])) # 007 042 105Use str() when the default form is acceptable, for example for ids or log messages. Use a format specification when the output has a fixed layout, such as prices with two decimals or zero-padded codes.
Floats deserve care. str(2.0) is '2.0', not '2'. If the receiving system expects integers, convert them first:
measurements = [2.0, 3.0, 4.5]
print(",".join(f"{m:g}" for m in measurements)) # 2,3,4.5The g format drops a trailing .0 and still keeps real fractions.
Items with their own string form
Any object can be joined once it is converted, because str() calls the object's __str__ method. Dates, decimals and your own classes work this way:
import datetime
days = [datetime.date(2026, 11, 26), datetime.date(2026, 12, 25)]
print(" | ".join(map(str, days))) # 2026-11-26 | 2026-12-25
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
points = [Point(0, 0), Point(1, 2)]
print(" -> ".join(map(str, points))) # (0, 0) -> (1, 2)If a class defines no __str__, str() falls back to __repr__, which for plain classes prints something like <__main__.Point object at 0x...>. That output is rarely what you want in joined text, so define __str__ on classes you plan to print.
str versus repr
repr() returns the developer-oriented form, often with quotes. For debugging output, it makes the type visible:
items = ["a", 1, "1"]
print(", ".join(map(str, items))) # a, 1, 1
print(", ".join(map(repr, items))) # 'a', 1, '1'With str, the integer 1 and the string "1" look identical. With repr, they differ. Prefer repr when you debug and str when you produce output for users or files.
Handling None and missing values
str(None) is 'None'. That is rarely wanted in a report or a data file. Decide what a missing value should look like and write that rule in the generator expression:
row = [1, None, 3]
print(",".join(map(str, row))) # 1,None,3
print(",".join("" if v is None else str(v) for v in row)) # 1,,3
print(",".join("N/A" if v is None else str(v) for v in row)) # 1,N/A,3If you want to drop missing values altogether, filter them out, which also removes their separators:
print(",".join(str(v) for v in row if v is not None)) # 1,3Check for None with is None, not with truthiness. A test such as if v would also skip 0, 0.0 and "", which are real values.
Other kinds of iterables
join accepts any iterable of strings, not only lists. What the iterable yields decides what you must convert.
Dictionaries
Iterating over a dictionary yields its keys. To join values or pairs, ask for them explicitly:
config = {"x": 1, "y": 2}
print(",".join(config)) # x,y
print(",".join(str(v) for v in config.values())) # 1,2
print("&".join(f"{k}={v}" for k, v in config.items())) # x=1&y=2The first line works only because the keys happen to be strings. If the keys were integers, it would raise a TypeError.
Sets
A set has no guaranteed order. Joining one gives output whose order may differ between runs for strings. Sort first when order matters:
tags = {"python", "strings", "join"}
print(", ".join(sorted(tags))) # join, python, stringsWhen items are numbers, sort before converting. Sorting after conversion orders by text, so "10" comes before "2":
nums = {10, 2, 33}
print(",".join(map(str, sorted(nums)))) # 2,10,33
print(",".join(sorted(map(str, nums)))) # 10,2,33Nested lists
join works on one level. For a table, join each row first and then join the rows:
rows = [[1, 2, 3], [4, 5, 6]]
text = "\n".join(" ".join(map(str, row)) for row in rows)
print(text)The output is:
1 2 3
4 5 6Passing the nested lists directly would fail on the first row, because a list is not a string.
Empty input and a single item
An empty iterable gives an empty string, and a single item gives that item with no separator:
print(repr(",".join([]))) # ''
print(",".join(["only"])) # onlyThis means you need no special case for empty data. It also means an empty list and a list containing one empty string look the same when joined: ",".join([""]) is also ''.
Bytes are a separate world
Text (str) and binary data (bytes) never mix in join. Use a bytes separator for bytes items:
print(b",".join([b"a", b"b"])) # b'a,b'
try:
print(",".join([b"a", b"b"]))
except TypeError as error:
print(error) # sequence item 0: expected str instance, bytes foundIf your data arrives as bytes but you want text, decode it first with .decode("utf-8"). Calling str(b"a") does not decode. It returns the text "b'a'", with the b and quotes included, which is a common surprise.
A reusable helper
When you convert and join in many places, a small helper keeps the rule in one spot:
def join_values(items, sep=", ", missing="", fmt=str):
"""Join any items into text, replacing None with `missing`."""
return sep.join(missing if item is None else fmt(item) for item in items)
print(join_values([1, None, 2.5])) # 1, , 2.5
print(join_values([1, None, 2.5], sep="|", missing="-")) # 1|-|2.5
print(join_values([1, 2.256], fmt=lambda v: f"{v:.1f}")) # 1.0, 2.3Do not build a helper like this until you repeat the same rule a few times. For one call site, a plain generator expression is clearer.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `",".join([1, 2])` | `TypeError: sequence item 0: expected str instance, int found` | `",".join(map(str, [1, 2]))` |
| `",".join(str([1, 2]))` | Joins the characters of `"[1, 2]"`, giving `[,1,,, ,2,]` | Convert each item, not the whole list |
| Joining a dictionary of integer keys | `TypeError` on the first key | Convert keys or use `.items()` with an f-string |
| `str(b"a")` for bytes | Gives `"b'a'"` | Use `.decode()` |
| `",".join(sorted(map(str, nums)))` | Text order: `10` before `2` | Sort the numbers, then convert |
| Leaving `None` unhandled | The text `None` appears in output | Replace or filter it explicitly |
Exercises
Exercise
The list scores = [90, 85.5, None, 70] must become the line 90 | 85.50 | n/a | 70.00. Write the one-line expression that produces it, using join.
Show answer
" | ".join("n/a" if s is None else f"{s:.2f}" for s in scores) produces "90.00 | 85.50 | n/a | 70.00". Note that applying :.2f to every number also formats 90 as 90.00, so the first item is "90.00", not "90". The exact line requested, with 90 unchanged, needs a rule that treats integers differently: " | ".join("n/a" if s is None else (str(s) if isinstance(s, int) and s == 90 else f"{s:.2f}") for s in scores) works for this one value, but a consistent rule such as formatting every number with two decimals is the better design, and the target line should be corrected to "90.00 | 85.50 | n/a | 70.00". The key points are the None check with is None and the f-string format specification inside the generator expression.
Exercise
Why does ",".join(str([1, 2, 3])) not raise an error, and what does it return? How do you fix it?
Show answer
str([1, 2, 3]) is the string "[1, 2, 3]". A string is an iterable of one-character strings, so join accepts it and puts the separator between all ten characters. The result is "[,1,,, ,2,,, ,3,]". The fix is to convert each item and join those: ",".join(str(n) for n in [1, 2, 3]), which returns "1,2,3".
Exercise
Given nums = {10, 2, 33}, what is the difference in output between ",".join(map(str, sorted(nums))) and ",".join(sorted(map(str, nums))), and which one is correct for ascending numeric order?
Show answer
The first returns "2,10,33" because it sorts the integers and then converts them. The second returns "10,2,33" because it sorts the strings alphabetically, character by character. The first is correct for numeric order.