如何在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 intostring2exactly at the same indices where spaces exist instring1, resulting in the desired output:"ESTD TD L ATPNP ZQ EPIE".
Step-by-Step Approach
- Map space positions: First, collect all the indices in
string1where 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 casestring1is longer thanstring2plus 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
string1has more spaces or is longer thanstring2can accommodate.
内容的提问来源于stack exchange,提问作者wkelly
相关产品推荐
相关产品推荐

