Sub topic 8
Joining numbers and other non-string items
This chapter assumes you know basic Python syntax, how lists and tuples work, and how to read a generator expression. You should also know what str.join does with a list of strings.
Why join insists on strings
str.join is called on the separator and takes an iterable of strings. It does not convert anything for you. If one item is an int, float, None or any other non-string, Python raises a TypeError.
numbers = [1, 2, 3]
try:
print(",".join(numbers))
except TypeError as error:
print(error) # sequence item 0: expected str instance, int foundThe message names the position of the first bad item. That helps when a long list has one stray value, such as a None from a missing record.
Python does not guess a conversion because there is more than one reasonable one. A float could be shown as 3.0, 3.00 or 3. Requiring you to choose keeps the output predictable.
Converting with str()
Convert each item to a string before joining. Two common ways are a generator expression and map.
numbers = [1, 2, 3]
print(",".join(str(n) for n in numbers)) # 1,2,3
print(",".join(map(str, numbers))) # 1,2,3Both produce the same result. The generator expression is more flexible, because you can change each item as you convert it. map(str, ...) is shorter when str() alone is enough.
prices = [3.5, 10, 2.25]
print(" | ".join(f"{p:.2f}" for p in prices)) # 3.50 | 10.00 | 2.25Here the f-string both converts and formats. Use this form when you need control over decimals, padding or other details.
Mixed and missing values
Real data often mixes types. str() handles any object, but the text it produces may not be what you want.
row = ["Ada", 36, None, True]
print(",".join(map(str, row))) # Ada,36,None,TrueNone becomes the text None, which is rarely what you want in a report or file. Decide how to treat missing values and write that rule into the conversion.
row = ["Ada", 36, None, True]
print(",".join("" if v is None else str(v) for v in row)) # Ada,36,,TrueThe conditional expression turns None into an empty string and converts everything else with str().
Common errors
- Forgetting to convert. Joining a list of numbers raises
TypeError. Convert first. - Calling join on the list.
numbers.join(",")fails because lists have nojoinmethod. Call it on the separator:",".join(...). - Joining a string. A string is an iterable of one-character strings, so
"-".join("abc")givesa-b-c. This is valid but often unintended when you meant to join a list. - Hiding
Noneas text.str(None)is"None". Handle missing values explicitly.
Choosing between the two forms
| Form | Best when | Example |
|---|---|---|
| `map(str, items)` | Plain conversion is enough | `",".join(map(str, nums))` |
| Generator expression | You format or filter each item | `",".join(f"{n:02d}" for n in nums)` |
Practice
Exercise
A list ids = [101, 102, 103] should become the string 101-102-103. Write the expression, and explain why "-".join(ids) fails.
Show answer
Use "-".join(map(str, ids)) or "-".join(str(i) for i in ids). The plain call fails because join requires every item to be a string, and the integers raise TypeError: sequence item 0: expected str instance, int found.
Exercise
Given row = ["x", None, 7], write an expression that produces x,,7.
Show answer
",".join("" if v is None else str(v) for v in row). The conditional turns None into an empty string, and str() converts the other items.