split and join
Break text into pieces and glue pieces into text. How games read commands.
Code runs right here in your browser. Nothing to install.
Learn it
split() breaks text into a list. join() glues a list back into 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.
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)
Try it yourself
+10 XPThe 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.
Capture the flag
+10 XPWhat 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.
Acronym maker
+20 XPAsk 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.