All sample questions / Python

What does print(s.count('an')) print? Python Data Types, Numbers and Strings

Block 1, Data Types, Numbers and Strings, question 14 of the Python sample

s = 'banana'
print(s.count('an'))

What does this print?

  1. A. 6
  2. B. 2
  3. C. 1
  4. D. 3
Show the answer and why each option is right or wrong

Answer, B. 2

A. 6
Counts individual matching letters instead of occurrences of the whole two letter substring.
B. 2
Correct. count scans the string from left to right and counts every non overlapping occurrence of the substring.
C. 1
Stops after finding the first occurrence instead of continuing to scan the rest of the string.
D. 3
Counts overlapping occurrences of the pattern as if each shifted starting position counted separately.

The count method finds every non overlapping occurrence of a substring, moving its search position past the end of each match before looking for the next one. It never counts a match that shares characters with a match it already found.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.