Next / Previous / Contents / Shipman's homepage

5.26. ParseResults: Result returned from a match

All parsers return an instance of this class. It can act like a list containing the strings that matched each piece of the corresponding parser. You may also use it like a dictionary, if you have used the .setResultsName() method on any of the component parsers to assign names to the text that matched that parser.

For an instance R, operations include:


To retrieve one of the matched tokens, you can treat the instance as a list.

You may also perform the usual list operations on a ParseResult such as replacing or deleting one of the values.

>>> nameList = pp.OneOrMore(pp.Word(pp.alphas))
>>> r = nameList.parseString('tungsten carbide drills')
>>> len(r)
>>> r[0]
>>> r[2]
>>> r[1] = 'fluoride'
>>> print r
['tungsten', 'fluoride', 'drills']
>>> del r[1]
>>> print r
['tungsten', 'drills']

If you have assigned names to any of the components of your parser, you can use the ParseResults instance as if it were a dictionary: the keys are the names, and each related value is the string that matched that component.

>>> firstName = pp.Word(pp.alphas).setResultsName('first')
>>> lastName = pp.Word(pp.alphas).setResultsName('last')
>>> fullName = firstName + lastName
>>> r = fullName.parseString('Doug Piranha')
>>> r['last']
>>> r['first']

Here are the methods available on a ParseResults instance.


This method returns the named items of R as a normal Python dict. Continuing the example above:

>>> r.asDict()
{'last': 'Piranha', 'first': 'Doug'}

This method returns R as a normal Python list.

>>> r.asList()
['Doug', 'Piranha']

Returns a copy of R.

.get(key, defaultValue=None)

Works like the .get() method on the standard Python dict type: if the ParseResult has no component named key, the defaultValue is returned.

>>> r.get('first', 'Unknown')
>>> r.get('middle', 'Unknown')
.insert(where, what)

Like the .insert() method of the Python list type, this method will insert the value of the string what before position where in the list of strings.

>>> r.insert(1, 'Bubbles')
>>> print r
['Doug', 'Bubbles', 'Piranha']

This method works like the .items() method of Python's dict type, returning a list of tuples (key, value).

>>> r.items()
[('last', 'Piranha'), ('first', 'Doug')]

Returns a list of the keys of named results. Continuing the Piranha example:

>>> r.keys()
['last', 'first']