Parsing Strings in Enclosed in Curly Braces

MRAB google at mrabarnett.plus.com
Fri May 15 13:25:55 EDT 2009


Chris Rebert wrote:
> On Fri, May 15, 2009 at 9:12 AM,  <xamalek at yahoo.com> wrote:
>> How do you parse a string enclosed in Curly Braces?
>>
>> For instance:
>>
>> x = "{ABC EFG IJK LMN OPQ}"
>>
>> I want to do x.split('{} ') and it does not work. Why does it not work
>> and what are EXCEPTIONS to using the split method?
> 
> .split() takes a *substring* to split on, *not* a set of individual
> characters to split on. Read the Fine Docs.
> 
>> That I want to split based on '{', '}' and WHITESPACE.
> 
> Well, you could use a regex, or you could just .find() where the
> braces are, slice them off the ends of the string, and then split the
> result on space.
> 
Here's a function which splits on multiple characters:

def split_many(string, delimiters):
     parts = [string]
     for d in delimiters:
         parts = sum((p.split(d) for p in parts), [])
     return parts



More information about the Python-list mailing list