PCEP-30-02 · Question #280
What is the expected output of the following code? data = 'abbabadaadbaccabc' print(data.count('ab', 1))
The correct answer is A. 2. str.count(sub, start) searches for non-overlapping occurrences of sub beginning at the given start index. With start=1, the search skips index 0, meaning the 'ab' at position 0 is excluded. The remaining string 'bbabadaadbaccabc' contains 'ab' at original indices 3 and 14…
Question
Options
- A2
- B4
- C3
- D5
How the community answered
(52 responses)- A83% (43)
- B12% (6)
- C4% (2)
- D2% (1)
Explanation
str.count(sub, start) searches for non-overlapping occurrences of sub beginning at the given start index. With start=1, the search skips index 0, meaning the 'ab' at position 0 is excluded. The remaining string 'bbabadaadbaccabc' contains 'ab' at original indices 3 and 14 - exactly 2 occurrences, making A correct.
Why the distractors fail:
- C (3) is the trap: calling
data.count('ab')with no start argument returns 3 (finds all occurrences at indices 0, 3, and 14). Many test-takers miss thatstart=1drops the first match. - B (4) and D (5) reflect overcounting errors, likely from misreading overlapping or adjacent characters like
'bb'or'ba'as'ab'.
Memory tip: Think of the start parameter as a bookmark - count('sub', n) tears off everything before page n and only counts within what's left. If the first match starts before your bookmark, it's gone.
Community Discussion
No community discussion yet for this question.