Parsing Strings in Enclosed in Curly Braces
John Machin
sjmachin at lexicon.net
Fri May 15 17:58:41 EDT 2009
On May 16, 3:25 am, MRAB <goo... at mrabarnett.plus.com> wrote:
> Chris Rebert wrote:
> > On Fri, May 15, 2009 at 9:12 AM, <xama... 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
Neat trick. However, from 2.6.2:
>>> help(sum)
Help on built-in function sum in module __builtin__:
sum(...)
sum(sequence[, start]) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start' (which defaults to 0). When the sequence is
empty, returns start.
Since when is a list a number? Perhaps the help needs clarification,
in line with the docs.
Cheers,
John
More information about the Python-list
mailing list