Python Arena
Step 4 of 5

split, join and strip

Text that a program reads often holds several values on one line: words in a sentence, numbers separated by commas. split cuts a string into a list of pieces. Without an argument, it cuts at spaces:

sentence = "the quick brown fox"
words = sentence.split()
print(words)
print(len(words), "words, the last is", words[-1])
print("a,b,,c".split(","))
Output
['the', 'quick', 'brown', 'fox']
4 words, the last is fox
['a', 'b', '', 'c']

With an argument, split cuts at that text instead. Two commas in a row give an empty piece between them.

The pieces are always strings. Numbers on a line must go through int, one at a time:

line = input("Two numbers: ")
parts = line.split()
a = int(parts[0])
b = int(parts[1])
print("Sum:", a + b)
Input
15 27
Output
Two numbers: 15 27
Sum: 42

Joining

join goes the other way: it joins a list of strings into one string. The string you call it on goes between the pieces. It looks backwards at first, but read it as "join these, with this between them":

words = ["red", "green", "blue"]
print(", ".join(words))
print("".join(words))
print(" -> ".join(sorted(words)))
Output
red, green, blue
redgreenblue
blue -> green -> red

Every item must be a string: ", ".join([1, 2]) is a TypeError. Turn numbers into strings first.

Stripping spaces

Users type extra spaces more often than you'd think. strip returns the string without spaces at its start and its end; the spaces in between stay:

answer = "   yes please  "
print("[" + answer + "]")
print("[" + answer.strip() + "]")
print(answer.strip() == "yes please")
Output
[   yes please  ]
[yes please]
True

split and join together make a handy pair. split() without an argument ignores any number of spaces between words, so " ".join(text.split()) turns any messy spacing into single spaces.

Your task

Challenge 1 of 3

Fill in the blanks so the program splits the line into words, prints how many there are, and prints them joined with dashes:

Words: one two three
3 words
one-two-three

Challenge 2

Write a program that reads lines of results until the user types an empty line. Each line has a name and then one or more scores, separated by spaces. For each line, the program prints the name and the total of the scores:

Results: Ada 12 15 9
Ada: 36
Results: Linus 7 8
Linus: 15
Results:

Challenge 3

Write the function tidy(text: str) -> str, which returns the text without spaces at its start and end, and with exactly one space between words. For example, tidy(" too many spaces ") returns 'too many spaces'.