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

如何在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

  1. 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
  2. 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, and if 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:35:35