数组元素修改技术问询:移除含C元素前的2-3个字符
First, let's break down what we need to do here: take your space-separated string (you called it an array) and modify any element containing the character 'C' by keeping only the part starting from the first 'C' onwards. This aligns perfectly with the transformations you showed (like turning "14(C55" into "C55" or "2(C14" into "C14").
Step-by-Step Approach
- Split the input string into individual elements using spaces as separators.
- For each element:
- If it includes 'C', extract the substring starting at the first occurrence of 'C'.
- If it doesn't have 'C', leave it exactly as is.
- Join all processed elements back into a single space-separated string.
Python Implementation
Here's a simple, readable code snippet that does this:
# Your original input string input_str = "C32 14(C55 2(C14 C10 3(C20 C10 2(O4 *149(H2 ZN C14 6(C5 6(C7 6(C3 6(C8 6(C11" # Split into individual elements elements = input_str.split() # Process each element processed_elements = [] for elem in elements: if 'C' in elem: # Grab the part starting from the first 'C' c_start_index = elem.index('C') processed_elements.append(elem[c_start_index:]) else: processed_elements.append(elem) # Combine back into the final string result = ' '.join(processed_elements) # Print the output print(result)
Result
Running this code will produce:
C32 C55 C14 C10 C20 C10 2(O4 *149(H2 ZN C14 C5 C7 C3 C8 C11
Quick note: There's a small mismatch with your desired output where you listed "C6" instead of "C3" (from the original "6(C3" element). This is almost certainly a typo in your expected result—our code correctly extracts "C3" from "6(C3", which follows the same pattern as all other transformations.
内容的提问来源于stack exchange,提问作者sergio

