join()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What is join()?
`join()` is the opposite of `split()`. It combines a list of strings into a single string, with a separator between each element.
team = ["Aquachu", "Pyrochu", "Florachu"]
result = ", ".join(team)
print(result)Notice the syntax: the separator calls `.join()`, not the list! This is a common source of confusion.
Exercise 2 — The join() Syntax
The pattern is: `separator.join(list)`. The separator is the string that goes between each element.
team = ["Aquachu", "Pyrochu", "Florachu"]
print(" - ".join(team))
print(" | ".join(team))
print("".join(team))When you use an empty string `""` as separator, the elements are joined with nothing between them!
Exercise 3 — join() Syntax
Which code correctly joins `["A", "B", "C"]` with a dash `-`?
Hint : In Python, it's the separator that calls the method, not the list.
Exercise 4 — Join the Team
Complete the code to join the Codémon names with `" & "`.
Hint : The separator goes before `.join()`, and the list goes inside the parentheses.
Exercise 5 — join() Output
moves = ["Splash", "Fireball"]
result = " | ".join(moves)
print(result)What is printed?
Hint : The separator is placed between elements, not around them.
Exercise 6 — join() Only Works with Strings
`join()` only works when all elements in the list are strings. If your list contains numbers, you need to convert them first.
levels = [30, 25, 28]
levels_str = []
for lv in levels:
levels_str.append(str(lv))
print(", ".join(levels_str))TypeError Warning
If you try `", ".join([1, 2, 3])` you'll get a `TypeError`. Always convert numbers to strings first with `str()`.
Exercise 7 — Join Numbers
Complete the code to join the levels into a single string separated by `-`.
Hint : You need to convert each number to a string first, then join with the right separator.
Exercise 8 — join() with Newlines
team = ["Aquachu", "Pyrochu", "Florachu"]
result = "\n".join(team)
print(result)How many lines are printed?
Hint : `\n` is a newline character. Each element goes on its own line.
Exercise 9 — Multiline Output
Complete the code to print each move on a new line using `join()`.
Hint : The newline character `\n` creates a new line between each element.
Exercise 10 — join() Results
Given `team = ["A", "B", "C"]`, match each `join()` call with its result.
Exercise 11 — Codémon Battle Log
Create a battle log formatter! 1. You have a list of moves: `["Splash", "Fireball", "Thunder", "Leaf Cut"]` — join them with ` > ` 2. You have a list of damage numbers: `[30, 45, 25, 50]` — join them as a string separated by `, ` 3. Print everything
moves = ["Splash", "Fireball", "Thunder", "Leaf Cut"]
damages = [30, 45, 25, 50]
# Create the move sequence
# Create damage report (numbers need conversion!)
# Print all