字符串空格选择性移除:按规则清除首尾、减半组间空格需求
Solution for Selective Space Removal in String
Let's break down how to solve this string manipulation problem exactly as you described. Here's a Python implementation that hits all your requirements:
import re # Your input string input_str = '[ A A A A A B B B B B B B B A A A A A ]' # Step 1: Remove leading/trailing spaces from the entire string stripped_str = input_str.strip() # Step 2: Extract content inside the brackets and split into character groups + spaces inner_content = stripped_str[1:-1] # Regex pattern to capture: either groups of repeated characters (with spaces) OR blocks of spaces parts = re.findall(r'((?:\w\s*)+)|(\s+)', inner_content) # Step 3: Process each part processed_segments = [] for char_group, space_block in parts: if char_group: # Remove all spaces within the same character group processed_segments.append(char_group.replace(' ', '')) else: # Halve the number of spaces between different groups processed_segments.append(' ' * (len(space_block) // 2)) # Step 4: Reconstruct the final string result = f'[{"".join(processed_segments)}]' print(repr(result)) # Output: '[AAAAA BBBBBBBB AAAAA]'
How this works:
- Strip首尾空格: The
strip()method removes any extra spaces at the very start and end of your input string (so something like' [ ... ] 'becomes'[ ... ]'). - Extract inner content: We slice off the opening
[and closing]to focus on the characters and spaces inside. - Split into groups: The regex splits the inner content into two types of segments:
- Character groups (like
A A A A AorB B B B B B B B) - Blocks of spaces between these groups
- Character groups (like
- Process each segment:
- For character groups: We remove all internal spaces to get a continuous string of the same character (e.g.,
A A A A A→AAAAA). - For space blocks: We take the length of the space block, divide it by 2 (using integer division to avoid fractions), and create a new space block of that length.
- For character groups: We remove all internal spaces to get a continuous string of the same character (e.g.,
- Reconstruct: We join all processed segments back together, wrap them in brackets, and get your desired output.
If you need to handle odd numbers of spaces between groups (e.g., 7 spaces → 4 instead of 3), just replace len(space_block) // 2 with round(len(space_block) / 2)—that will round to the nearest integer instead of truncating.
内容的提问来源于stack exchange,提问作者kdba
相关产品推荐
相关产品推荐

