Back

Slicing strings - Answers

 

Assume you are using: myPhrase = "I don't like Mondays!" 

Q1. print(myPhrase[2:6])        don'
Q2. print(myPhrase[0:7])        I don't
Q3. print(myPhrase[:3])          I d
Q4. print(myPhrase[10:7])      the empty string
Q5. print(myPhrase[8:11])      lik
Q6. print(myPhrase[13:])        Mondays!
Q7. print(myPhrase[:])            I don't like Mondays!
Q8. print(myPhrase[-4:-1])     ays
Q9. print(myPhrase[-8:])        Mondays!
Q10. print(myPhrase[:-15])    I don'
Q11. print(myPhrase[0])        I
Q12. print(myPhrase[13])      M 
Q13. print(myPhrase[5])        '
Q14. print(myPhrase[-1])      !
Q15. print(myPhrase[-5])      d
Q16. print(myPhrase[-105])   an error is returned because the index used is out of the range of possible indexes.
Q17. print(myPhrase[105])    an error is returned because the index used is out of the range of possible indexes.
Q18. print(myPhrase[2.5])     an error is returned because the index must be an integer (whole number).
Q19. print(myPhrase['a'])      an error is returned because the index must be an integer (whole number). 
Q20. print(myPhrase[true])   an error is returned because the index isn't defined anywhere.

Q21 and Q22. When you enter and run this code:

item = "boot"
print(item[3])
item[3] = "k"
print(item)

You will find that you get an error: TypeError: 'str' object does not support item assignment. This is because strings cannot be changed once created. Although we can index through each position in a string, we can't change any of the data in any of the positions. We say that strings are 'immutable'. The best we can do is to create a new string from an old one.
Q23. We can use slicing here. item[:-1] will get all the letters from the start of any word up to but not including the last letter. We can then use concatenation to add a 'k' on the end.

item = input('Please enter a word >>> ')
print(item)
newItem = item[:-1]+'k'
print(newItem)

Back