Next / Previous / Contents / Shipman's homepage

6.2. countedArray: Parse N followed by N things

pp.countedArray(parser, intExpr=None)

This rather specialized function creates a parser that matches some count, followed by that many occurrences of a pattern matching some parser, like "3 Moe Larry Curly". This function deposits a list of the values into the returned ParseResults, omitting the count itself. Note that the integers in this example are returned as type str, not type int.

>>> number = pp.Word(pp.nums)
>>> print pp.countedArray(number).parseString('3 18 37 33')
[['18', '37', '33']]
>>> countedQuoted = pp.countedArray(pp.QuotedString('"'))
>>> print countedQuoted.parseString('3 "Moe" "Larry" "Curly Joe"')
[['Moe', 'Larry', 'Curly Joe']]

If the count is for some reason not an integer in the usual form, you can provide an intExpr keyword argument that specifies a parser that will match the count and return it as a Python int.

>>> def octInt(toks): # Convert octal to int
...     return int(toks[0], 8)
... 
>>> octal = pp.Word('01234567').setParseAction(octInt)
>>> print octal.parseString('77')
[63]
>>> print pp.countedArray(number, intExpr=octal).parseString(
...     '11 1 2 3 4 5 6 7 8 9')
[['1', '2', '3', '4', '5', '6', '7', '8', '9']]