star98
star98

Reputation: 327

Using re.split() for two { } in python

I am trying to use re.split() so that I can write a madlibs program in python.

I have been attempting to make it so that it splits every set of brackets, example {noun}. So far I have only been able to successfully split the first bracket, but not the second. I am trying to read the documentation on it but I am still really confused. I've looked at other examples of using re.split() on multiple items but all it does is confuse me. Can someone please explain to me in depth how to get past this problem? Thank you greatly.

ex code:

re.split('{') <--- Works re.split('{', '}') <-- doesn't work

Upvotes: 1

Views: 145

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174816

As said in the comment, you need to separate the symbols using a logical OR operator |. So that the regex engine would split the input string according to { or } symbols. And don't forget to define the regex as raw string.

re.split(r'{|}', str)

OR

Put them inside a charcter class.

re.split(r'[{}]', str)

Example:

>>> re.split(r'{|}', "{noun}")
['', 'noun', '']
>>> re.split(r'[{}]', "{noun}")
['', 'noun', '']

Upvotes: 1

Related Questions