Browser lab15 min+60 XP

split and join

Break text into pieces and glue pieces into text. How games read commands.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

split() breaks text into a list. join() glues a list back into text.

Key words
"hack the planet""hack""the""planet""hack-the-planet".split()"-".join(words)
Text becomes a list of words, then a new piece of text.

text.split() breaks a string into a list of words at the spaces. Give it a separator to split somewhere else: "a,b,c".split(",") gives ['a', 'b', 'c'].

The opposite is join: "-".join(["a", "b", "c"]) gives "a-b-c". The string before the dot is the glue.

Text adventures use split to read commands. "take red key".split(maxsplit=1) gives ['take', 'red key']: the verb and everything after it.

Real life linkA spreadsheet file is lines of text with commas between the values. Splitting each line on the comma turns it back into separate items.
Example code
sentence = "hack the planet"
words = sentence.split()
print(words, len(words))
print(" ".join(reversed(words)))
row = "Nova,14,Stealth"
name, age, skill = row.split(",")
print(name, int(age) + 1, skill)
verb, noun = "take red key".split(maxsplit=1)
print(verb, "|", noun)
TASK 2

Try it yourself

+10 XP

The scores are stored as one string. Split it, convert each part to an int, and print the total: Total: 315.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What does "-".join(["x", "y", "z"]) produce?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Acronym maker

+20 XP

Ask for a phrase and print its acronym in capitals (the first letter of each word, joined together). portable network graphics becomes PNG. Use split and join.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.