0

How to split based off two characters "[" & "]" in a string. For example calling .split() on the following would give...

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"

x.split()
print(x)

would give

["I just wanted you to know ... more lyrics", " be Puerto Rican day parade floatin' ... more lyrics]

This is different from the duplicate because its not splitting by multiple delimiters, its splitting by text enclosed in brackets when the text isnt necessarily known...

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
izzyp
  • 163
  • 1
  • 7
  • try x.split(\[|\\\]). Checking this [link](https://stackoverflow.com/questions/5993779/use-string-split-with-multiple-delimiters), may also help you. – AntoineLB May 14 '18 at 09:58
  • @xXxpRoGrAmmErxXx This is not splitting by multiple delimiters. This is splitting by text enclosed in brackets. – Aran-Fey May 14 '18 at 10:08
  • @SvenMarnach How exactly does that dupe apply to this question? See ^ this comment. – Aran-Fey May 14 '18 at 10:15
  • I dont think this applies as a dupe? – izzyp May 14 '18 at 10:24
  • **Moderator Note**: Please do not vandalize your posts. Once you post a question, they belong to the site and its users. Even if it is no longer useful to you, it might be helpful to someone in the future. The answerers would have also put an effort in writing their answer, which would no longer be useful if you have removed the content from the post. Also, note that by posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted. – Bhargav Rao May 18 '18 at 01:43

1 Answers1

1

You can use re.split("[\[\]]", x)

Using Regex:

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"""

print(filter(None,re.split("[\[\]]", x)[::2]))

Output:

['\nI just wanted you to know\n...more lyrics\n', "\nI be Puerto Rican day parade floatin'\n... more lyrics"]
Rakesh
  • 81,458
  • 17
  • 76
  • 113