String methods - Answers
Q1. The code should output:
battleships and cabbages
BATTLESHIPS AND CABBAGES
6
4
Q2. The same as before. It doesn't make any difference if you use a pair of single quotes or double quotes.
Q3. If you search for the substring 'bag', it should return 19 as that is where the first occurrence of bag is.
Q4. The program should add an extra line with the letter 't' replaced with 'x':
Baxxleships and cabbages
Q5. To change every instance of the letter 'a' so it is a capital 'A':
print(myWord.replace('a','A'))
Q6. Capital letters are changed to lower case and lower case letters are changed to capital letters using the swapcase() method:
print(myWord.swapcase())
Q7. To write a line of code to print the myWord string so that it is left hand justified, exactly 30 characters long and any padding you need to get it to be exactly 30 characters long is done using a capital V.
print(myWord.ljust(30,'V'))
Q8. N/A
Q9. To reverse a string and put it in capitals, take each letter in turn, call the capitalisation method and then concatenate it in front of a temporary variable, making sure that the temporary variable is initialised to empty to start with e.g.
phrase = 'Hello world'
rev = ''
for letter in phrase:
rev = letter.upper() + rev
print(rev)
Copy and paste this code (or your own) into www.pythontutor.com to visualise what is happening.