split and join
Python · Unit 6: Strings
- Full plan
- Python
- 10 exercises
split() cuts a string and returns a list. With nothing in the parentheses, it cuts at the spaces.
With a string inside, it cuts there: split(",") cuts at every comma.
phrase = "I like ice cream"
print(phrase.split())
fruits = "pear,plum,kiwi"
print(fruits.split(","))Prints
['I', 'like', 'ice', 'cream'] ['pear', 'plum', 'kiwi']
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Multiple choice
What does this code do?
4. Predict the output
What does this code print?
5. Find the bug
This program should print "bread, milk, tea". Which line has the error?
6. Complete the code
Complete it so it prints "good night".
7. Predict the output
There is no
split()here. What does it print?8. Put the lines in order
Order the function that flips the order of the words in a sentence.
9. Find the case that fails
count_words(phrase)should return how many words the sentence has, or 0 if it is empty. Which call breaks it?10. Write the code
Write
initials(name), which returns the initials in capitals. For example,initials("ann marie reed")gives"AMR". Hint:word[0].upper()is the first letter of a word, in uppercase.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.