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

如何在Python中将一个字符串的空格位置复制到无空格目标字符串?

Solution: Mirror Space Positions Between Strings

First, let's restate the problem clearly to make sure we're aligned:

We have two strings:

  • string1: Contains spaces at specific positions (e.g., "This is a piece of text")
  • string2: A space-free string (e.g., "ESTDTDLATPNPZQEPIE")
    We need to insert spaces into string2 exactly at the same indices where spaces exist in string1, resulting in the desired output: "ESTD TD L ATPNP ZQ EPIE".

Step-by-Step Approach

  • Map space positions: First, collect all the indices in string1 where a space occurs.
  • Insert spaces in reverse: Since inserting a space shifts all subsequent characters right, we’ll insert spaces starting from the last position and moving backward. This avoids messing up the indices of unprocessed spaces.
  • Handle edge cases: Add a check to skip inserting spaces that would fall beyond the length of string2 (in case string1 is longer than string2 plus the number of spaces).

Python Implementation

Here's a clean, working code example that follows this logic:

def mirror_spaces(reference_str, target_str):
    # Gather all indices where the reference string has spaces
    space_indices = [idx for idx, char in enumerate(reference_str) if char == ' ']
    
    # Convert target string to a list (strings are immutable in Python, lists are easier to modify)
    target_chars = list(target_str)
    
    # Insert spaces in reverse order to avoid index shifting issues
    for idx in reversed(space_indices):
        # Only insert if the index is within the bounds of the current target list
        if idx <= len(target_chars):
            target_chars.insert(idx, ' ')
    
    # Convert the modified list back to a string and return
    return ''.join(target_chars)

# Test with your example inputs
string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"
result = mirror_spaces(string1, string2)
print(result)  # Output: ESTD TD L ATPNP ZQ EPIE

Breakdown of the Code

  • Space index collection: For the example string1, this gives us [4, 7, 9, 15, 18] (0-indexed positions of spaces).
  • Reversed insertion: Inserting at index 18 first, then 15, etc., ensures each insertion doesn’t alter the positions we still need to process.
  • Bounds check: Prevents errors if string1 has more spaces or is longer than string2 can accommodate.

内容的提问来源于stack exchange,提问作者wkelly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:11:11