- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
CS50x threads to aide as a supplementary resource › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › MITx 6.00.1x Introduction to Computer Science and Programming Using Python › Week 1: Python Basics › Substring search in Python: Counting ‘bob’ in a string
Great question! The reason why we use i+3
and not i+2
when checking the substring is because of how Python string slicing works, especially when specifying ranges in slices.
When you slice a string like s[start:end]
, the start index is inclusive (the slice starts at start
), but the end index is exclusive (the slice stops just before end
).
i+3
:i
, we need to include the indices i
, i+1
, and i+2
.s[i:i+3]
, because:i
is the starting index.i+3
ensures that the substring includes characters at positions i
, i+1
, and i+2
(but excludes the character at index i+3
).Let’s take s = 'azcbobobegghakl'
.
i = 3
, the slice s[3:6]
means:3
(which is 'b'
).6
(which is 'o'
at index 4
, and 'b'
at index 5
).s[3:6]
gives 'bob'
(which is what we want to check).i+2
instead?If we wrote s[i:i+2]
, we would only get a substring of 2 characters, which is not enough to check for 'bob'
.
s[3:5]
would give 'bo'
, which is not equal to 'bob'
.i
and i+1
(but not i+2
).We use i+3
to ensure that we are checking a substring of exactly 3 characters (s[i:i+3]
), which includes the characters at indices i
, i+1
, and i+2
.
So, the correct way to check for 'bob'
is with:
if s[i:i+3] == 'bob': # Checks the substring of length 3
Source: Created with help of AI tool