IT, Programming, & Web Development › 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
- This topic is empty.
-
AuthorPosts
-
September 14, 2024 at 2:35 pm #3529
Great question! The reason why we use
i+3
and noti+2
when checking the substring is because of how Python string slicing works, especially when specifying ranges in slices.String slicing in Python:
When you slice a string like
s[start:end]
, the start index is inclusive (the slice starts atstart
), but the end index is exclusive (the slice stops just beforeend
).Why
i+3
:- If we want to check for a substring of exactly 3 characters starting at position
i
, we need to include the indicesi
,i+1
, andi+2
. - To achieve this, we specify the slice as
s[i:i+3]
, because: i
is the starting index.i+3
ensures that the substring includes characters at positionsi
,i+1
, andi+2
(but excludes the character at indexi+3
).
Example:
Let’s take
s = 'azcbobobegghakl'
.- When
i = 3
, the slices[3:6]
means: - Start at index
3
(which is'b'
). - Stop just before index
6
(which is'o'
at index4
, and'b'
at index5
). - The slice
s[3:6]
gives'bob'
(which is what we want to check).
What happens if we use
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'
.- For example,
s[3:5]
would give'bo'
, which is not equal to'bob'
. - This is because the slice would only include characters at positions
i
andi+1
(but noti+2
).
Conclusion:
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 indicesi
,i+1
, andi+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
- If we want to check for a substring of exactly 3 characters starting at position
-
AuthorPosts
- You must be logged in to reply to this topic.