如何在Python中按[]包裹的未知文本分割字符串?
Split string using unknown text wrapped in square brackets as delimiter
Got it, let's solve this problem where you need to split a string using the unknown text wrapped in [ and ] as the delimiter. The key challenge here is that the content inside the brackets is dynamic—you can't use a fixed value with plain str.split(), so regular expressions are the way to go.
The Problem Breakdown
Your input string looks like this:
x = "[Chorus: Rihanna & Swizz Beatz] I just wanted you to know ...more lyrics [Verse 2: Kanye West & Swizz Beatz] I be Puerto Rican day parade floatin' ... more lyrics"
And you want to extract just the lyric content, ending up with:
["I just wanted you to know ...more lyrics", "I be Puerto Rican day parade floatin' ... more lyrics"]
Solution Code
Here's a straightforward implementation using Python's re module:
import re x = "[Chorus: Rihanna & Swizz Beatz] I just wanted you to know ...more lyrics [Verse 2: Kanye West & Swizz Beatz] I be Puerto Rican day parade floatin' ... more lyrics" # Split the string using any bracket-wrapped content as the delimiter split_parts = re.split(r'\[.*?\]', x) # Clean up the results: remove empty strings and trim extra whitespace clean_lyrics = [part.strip() for part in split_parts if part.strip()] print(clean_lyrics)
How It Works
- Regular Expression Pattern:
r'\[.*?\]'\[: Escapes the left square bracket (since[has special meaning in regex) to match it literally.*?: Uses non-greedy matching to capture any characters until the first](this prevents it from matching all content between the first[and last]in the string)\]: Escapes the right square bracket to match it literally
- Result Cleaning:
re.split()will return a list that includes an empty string at the start (since the input begins with[) and extra whitespace around the lyric sections.- The list comprehension uses
strip()to remove leading/trailing whitespace, andif part.strip()filters out any empty leftover strings from the split.
Output
Running this code will produce exactly the expected output:
["I just wanted you to know ...more lyrics", "I be Puerto Rican day parade floatin' ... more lyrics"]
内容的提问来源于stack exchange,提问作者izzyp
相关产品推荐
相关产品推荐

