Hosted by CoCalc
Download
Kernel: Python 3 (system-wide)

Exercise 10.1

Loop through the following string printing out each character.

book_title = "The Chimpanzees of Gombe"
for c in book_title: print(c)

Exercise 10.2

Loop through the following string in reverse printing out each character.

  • Hint: See Notebook 6 for how to reverse a string.

book_title = "The Chimpanzees of Gombe"
for c in book_title[::-1]: print(c)

Exercise 10.3

In Notebook 5 we introduced the len() function which returns the length of a string. Write your own code that counts the number characters in a string and then prints it out.

  • Hint: You will need a tally variable to keep a count of the number of characters.

book_intro = "Temper tantrums are a characteristic performance of the infant and young juvenile chimpanzee. The animal screaming loudly either leaps into the air with its arms above its head or hurls itself to the ground, writhing about and often hitting itself against surrounding objects."
count = 0 for c in book_intro: count += 1 print(count) print(len(book_intro))

Exercise 10.4

Many common tasks in Python usually have an inbuilt method. Counting the number of occurrences of a character in a string is a common thing to do.

Try googling "python count character in string" to see if you can discover a simpler method for counting "f"s in the following sentence. Then use that method to count "f"s.

  • Hint: Remember to count both lowercase and uppercase "f"s.

sentence = 'The embryo of Festuca fusca, a native plant species of Old-World countries, is almost half the full length of its grain.'
print( sentence.count('f') + sentence.count('F') )