如何查找字符串中以'a'开头、以'b'结尾的子串?
Extracting All 'a'-to-'b' Substrings from a String
Got it, let's break down how to solve this problem. You need to pull out every substring from 'abdadqdqbdabdabdawb' that starts with 'a' and ends with 'b', with the expected output being ['ab', 'adqdqb', 'ab', 'ab', 'awb']. Here's a straightforward Python solution tailored to your needs:
Step-by-Step Code Solution
s = 'abdadqdqbdabdabdawb' matched_substrings = [] current_start = None for index, char in enumerate(s): # Mark the start of a potential substring when we hit an unpaired 'a' if char == 'a': current_start = index # Extract the substring when we hit a 'b' that pairs with the last 'a' elif char == 'b' and current_start is not None: matched_substrings.append(s[current_start:index + 1]) # Reset start to avoid reusing the same 'a' for multiple 'b's current_start = None print(matched_substrings)
How This Logic Works
- We initialize an empty list
matched_substringsto store our results, andcurrent_startto track the position of the last unpaired'a'we found. - As we loop through each character in the string:
- When we encounter an
'a', we updatecurrent_startto its index—this sets the starting point for our next candidate substring. - When we hit a
'b'and we have an unpaired'a'(meaningcurrent_startisn’tNone), we slice the string fromcurrent_startto the current index (inclusive), add this substring to our list, then resetcurrent_startso we don’t pair that same'a'with another'b'.
- When we encounter an
- This ensures we capture non-overlapping, sequential
a-to-bsubstrings exactly as your expected output requires.
Output Verification
Running the code above will print:
['ab', 'adqdqb', 'ab', 'ab', 'awb']
Which matches your desired result perfectly.
内容的提问来源于stack exchange,提问作者Jonas Virkutis
相关产品推荐
相关产品推荐

