Slicing strings
Slicing strings is the phrase given to picking out a substring of a string. It follows this pattern:
myPhrase = "I don't like Mondays!"
print(myPhrase[m:n])
where 'm' is an index that points to the position of the first character and 'n' is an index that points up to but not including the last position. Remember:
-
- we use square brackets to pick out the slice
- Python starts counting positions from 0 not 1
- 'm' must be less than 'n' or an empty string is returned
- negative indices are possible. The last character in a string starts at position -1, the second last character -2 and so on.
- if we miss out m e.g. print(myPhrase[:n]) we assume m is zero.
- if we miss out n e.g. print(myPhrase[m:]) we assume that n goes to the end of the string.
- if we miss out the colon, we are picking out a single character.
Use this for the following questions:
myPhrase = "I don't like Mondays!"
Predict the answers to these questions. When you think you know what the output will be for each question, run each print line and see if you were correct.
Q1. print(myPhrase[2:6])
Q2. print(myPhrase[0:7])
Q3. print(myPhrase[:3])
Q4. print(myPhrase[10:7])
Q5. print(myPhrase[8:11])
Q6. print(myPhrase[13:])
Q7. print(myPhrase[:])
Q8. print(myPhrase[-4:-1])
Q9. print(myPhrase[-8:])
Q10. print(myPhrase[:-15])
Q11. print(myPhrase[0])
Q12. print(myPhrase[13])
Q13. print(myPhrase[5])
Q14. print(myPhrase[-1])
Q15. print(myPhrase[-5])
Q16. print(myPhrase[-105])
Q17. print(myPhrase[105])
Q18. print(myPhrase[2.5])
Q19. print(myPhrase['a'])
Q20. print(myPhrase[true])
Q21. Predict what will happen when you enter and run this code:
item = "boot"
print(item[3])
item[3] = "k"
print(item)
Q22. Now enter and run the code. Was your prediction correct?
Q23. Write a program that creates a new item held in a variable called newItem by stripping off the last letter of a word held in a variable called item and then adding the letter 'k' to the end. The result should be printed out.