PCAP Strings Practice Question
Which of the following expressions raises a ValueError?
⚠ Common exam trap
Python Institute often tests the subtle difference between `index()` (which raises an exception) and `find()`/`rfind()` (which return -1), trapping candidates who assume all substring search methods behave identically on failure.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
'abc'.index('d')
Calling `'abc'.index('d')` raises a `ValueError` when the substring is not found. The `str.index()` method in Python is designed to raise this exception for missing substrings, unlike `str.find()` and `str.rfind()`, which return -1.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
'abc'.index('a')
Why it's wrong here
The substring 'a' is present at position 0 in 'abc', so str.index() successfully returns 0. This method only raises ValueError when the search substring is entirely absent from the target string. Since 'a' exists, this call completes normally and is not the source of a ValueError.
- ✗
'abc'.find('d')
Why it's wrong here
str.find() never raises a ValueError for a missing substring; instead, it returns the integer sentinel -1. Because 'd' is not contained in 'abc', this expression evaluates to -1, which is a valid result, not an exception. The-1 return value is how find signals 'not found' without disrupting program flow.
- ✗
'abc'.rfind('d')
Why it's wrong here
str.rfind() also returns -1 when its substring argument is not found, even though it searches the string from right to left. The reversed search direction does not change the exception behavior: a missing substring still results in a silent -1 rather than an error. Thus, this call also completes without raising ValueError.
- ✓
'abc'.index('d')
Why this is correct
Here, str.index() is invoked with 'd', which does not occur in the string 'abc'. Unlike find/rfind, index is designed to raise ValueError when the substring is absent, treating that condition as an exceptional event. Because 'd' is missing, this expression raises ValueError, making it the correct answer.
Go deeper
Related to this question
About these practice questions
One of 421 original PCAP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCAP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCAP exam.