Sub topic 3
Joining numbers and other non-string items
Assume you know basic Python syntax, lists, tuples, loops, and generator expressions. String methods return new values because strings are immutable.
Joining non-string items
str.join combines an iterable of strings. It does not automatically convert numbers or other objects. Convert each item before joining:
numbers = [4, 8, 15]
text = ", ".join(str(number) for number in numbers)
print(text) # 4, 8, 15Passing numbers directly raises TypeError, because its items are integers.
Why `join` beats concatenating in a loop
Repeated + creates a new string on each iteration. join assembles the final string from all parts and makes the separator explicit.
parts = ["red", "green", "blue"]
result = " | ".join(parts)
print(result) # red | green | blueA loop often needs extra logic to avoid a trailing separator. Prefer join when you already have separate pieces.
When split and join undo each other
For a safe separator, these operations can reconstruct the original text:
text = "red,green,blue"
parts = text.split(",")
print(",".join(parts)) # red,green,blueThis is not always a true round trip. Whitespace splitting discards leading, trailing, and repeated whitespace. An explicit separator preserves empty fields, but the separator must not have a meaning inside the data.
Splitting on patterns
Use re.split when one fixed separator is not enough. A regular expression is a pattern describing text:
import re
text = "alpha, beta;gamma"
fields = re.split(r"[,;]\s*", text)
print(fields) # ['alpha', 'beta', 'gamma']A capturing group keeps the matched separators in the result:
print(re.split(r"([,;])", "a,b;c"))
# ['a', ',', 'b', ';', 'c']When `split` is not enough
Plain split(",") cannot understand quoted separators. It incorrectly breaks "b,c" into two fields. Use csv.reader for CSV rules:
import csv
row = 'a,"b,c",d'
print(next(csv.reader([row]))) # ['a', 'b,c', 'd']Exercise
How can you join [1, 2, 3] with a hyphen?
Show answer
Use "-".join(str(number) for number in [1, 2, 3]).