Next / Previous / Contents / Shipman's homepage

5.13. Group: Group repeated items into a list

pp.Group(parser)

This class causes the value returned from a match to be formed into a list. The parser argument is some parser that involves repeated tokens such as ZeroOrMore or a delimitedList.

>>> lb = pp.Literal('{')
>>> rb = pp.Literal('}')
>>> wordList = pp.OneOrMore(pp.Word(pp.alphas))
>>> pat1 = lb + wordList + rb
>>> print pat1.parseString('{ant bee crow}')
['{', 'ant', 'bee', 'crow', '}']
>>> pat2 = lb + pp.Group(wordList) + rb
>>> print pat2.parseString('{ant bee crow}')
['{', ['ant', 'bee', 'crow'], '}']

In the example above, both pat1 and pat2 match a sequence of words within {braces}. In the test of pat1, the result has five elements: the three words and the opening and closing braces. In the test of pat2, the result has three elements: the open brace, a list of the strings that matched the OneOrMore parser, and the closing brace.