Python新手求助:如何调整列表中含[]的字符串格式?
Hey there! No worries at all—every Pythonista starts somewhere 😊 Let's figure out how to adjust your string list exactly as you want.
Approach
The key here is to identify elements that contain a bracket-style range (like [7:0]), then rearrange the non-bracket parts to come before the range, in reversed order relative to their original position around the range. Here's a step-by-step way to do it:
- For each string in your list, check if it has a range pattern like
[X:Y]. - If it does, separate that range part from the rest of the text.
- Split the remaining text into individual parts, reverse their order, then combine them back with the range part at the end.
- If the string doesn't have a range, leave it as-is.
Solution Code
import re original_data = ['A', 'B', 'C', 'X [7:0] Y', '[3:0] K'] # Regex pattern to match [number:number] range_pattern = r'\[\d+:\d+\]' processed_data = [] for item in original_data: # Look for the range pattern in the current item range_match = re.search(range_pattern, item) if range_match: # Extract the range part (e.g., '[7:0]') range_part = range_match.group() # Get the remaining text, strip extra spaces, split into parts remaining_text = item.replace(range_part, '').strip() text_parts = remaining_text.split() # Reverse the parts and combine with the range reordered_text = ' '.join(reversed(text_parts)) processed_item = f"{reordered_text} {range_part}" processed_data.append(processed_item) else: # No range found, keep the original item processed_data.append(item) print(processed_data) # Output: ['A', 'B', 'C', 'Y X [7:0]', 'K [3:0]']
Explanation
- We use the
remodule to search for the range pattern (\[\d+:\d+\]matches any string like[0:3],[7:0], etc.). - For items with a range, we isolate that range, then take the rest of the text, split it into words, reverse those words, and put them before the range.
- Items without a range are added to the result list unchanged.
This works perfectly for your given example, and it's flexible enough to handle similar cases where the range is surrounded by single words on either side (or just one word like in your [3:0] K case).
内容的提问来源于stack exchange,提问作者H.K
相关产品推荐
相关产品推荐

