Strings in Python
Answers are for parents and teachers.
1
What is len("good morning")? Count each character.
12: 4 letters, 1 space and 7 letters.
2
Draw the index sheet for "garden". Which letter is text[2] and which is text[-2]?
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | g | a | r | d | e | n |
| 2 | 0 | 1 | 2 | 3 | 4 | 5 |
| 3 | −6 | −5 | −4 | −3 | −2 | −1 |
g0 a1 r2 d3 e4 n5, and -6 to -1 below. text[2] is r and text[-2] is e.
3
What does this loop show?
Python
1for letter in "go": 2 print(letter)
g on one line and o on the next.
4
A friend writes text[0] = "H" to change the first letter of “hello”. What happens and what can be done instead?
Python stops with a TypeError because a string cannot be changed. Make a new string, for example text = text.upper().
5
What do "5" + "2" and 5 + 2 give? Why do they differ?
52 and 7. With quotation marks the digits are text and are joined; without them they are numbers and are added.