You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串空格选择性移除:按规则清除首尾、减半组间空格需求

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:

  1. Strip首尾空格: The strip() method removes any extra spaces at the very start and end of your input string (so something like ' [ ... ] ' becomes '[ ... ]').
  2. Extract inner content: We slice off the opening [ and closing ] to focus on the characters and spaces inside.
  3. Split into groups: The regex splits the inner content into two types of segments:
    • Character groups (like A A A A A or B B B B B B B B)
    • Blocks of spaces between these groups
  4. 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.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:51