为何添加-len(t)与+len(t)才能正确查找字符串中子串的所有位置?
Hey there! Let's break down exactly why those two changes fixed your substring matching issue. I'll use concrete examples to make it crystal clear.
First Fix: Limiting the Loop Range with len(big_str) - len(sub_str)
Let's start with a simple example: suppose your big string is "abcabcabc" (length 9) and your substring is "abc" (length 3).
The last possible starting index where the substring can fit entirely into the big string is 6—because 6 + 3 = 9, which is exactly the end of the big string. If you loop all the way to len(big_str) (i.e., index 8), when you get to i=7 or i=8, trying to slice 3 characters from those positions will result in a shorter string ("bc" or "c"), which can never match your 3-character substring.
By adjusting the range to stop at len(big_str) - len(sub_str) + 1 (the core idea behind your subtraction change), you restrict the loop to only check starting indexes where the substring can fully fit. This eliminates useless checks and ensures you don't miss any valid positions.
Second Fix: Slicing with i:i+len(sub_str)
To check if the substring starts at index i, you need to compare apples to apples—meaning you need to grab a chunk of the big string that's the exact same length as your substring.
If your original code didn't add the substring length to the slice (e.g., you used big_str[i] or big_str[i:i]), you were either comparing a single character to the entire substring (which will never match unless the substring is length 1) or comparing an empty string to your substring.
Adding len(sub_str) to the slice endpoint gives you a chunk of the big string that matches the substring's length. For our example, big_str[0:3] gives "abc", which correctly compares to your substring.
Example Code Comparison
Broken Code (Returns Empty List)
def find_matches(big_str, sub_str): matches = [] sub_len = len(sub_str) # Loop runs too far, checking invalid positions for i in range(len(big_str)): # Slice doesn't grab enough characters if big_str[i] == sub_str: matches.append(i) return matches
Fixed Code (Finds All Matches)
def find_matches(big_str, sub_str): matches = [] sub_len = len(sub_str) # Only check valid starting positions for i in range(len(big_str) - sub_len + 1): # Grab a slice of the correct length to compare if big_str[i:i+sub_len] == sub_str: matches.append(i) return matches
Quick Recap
- Range fix: Ensures you only check starting indexes where the substring can fit entirely in the big string—no more wasted checks on positions that can't possibly match.
- Slice fix: Grabs a segment of the big string that's the same length as your substring, allowing a valid equality comparison to find matches.
内容的提问来源于stack exchange,提问作者zostrom

