• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #3529

    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.

    String slicing in Python:

    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).

    Why i+3:

    • If we want to check for a substring of exactly 3 characters starting at position i, we need to include the indices i, i+1, and i+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 positions i, i+1, and i+2 (but excludes the character at index i+3).

    Example:

    Let’s take s = 'azcbobobegghakl'.

    • When i = 3, the slice s[3:6] means:
    • Start at index 3 (which is 'b').
    • Stop just before index 6 (which is 'o' at index 4, and 'b' at index 5).
    • 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 and i+1 (but not i+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 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

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.
Scroll to Top