Parsing a dictionary from a format string

Ian Kelly ian.g.kelly at gmail.com
Mon Jun 20 15:34:46 EDT 2011


On Mon, Jun 20, 2011 at 12:14 PM, Tim Johnson <tim at johnsons-web.com> wrote:
> Currently using python 2.6, but am serving some systems that have
> older versions of python (no earlier than.
> Question 1:
>  With what version of python was str.format() first implemented?

2.6

> Question 2:
>  Given the following string:
>    S = 'Coordinates: {latitude}, {longitude}'
>  Is there a python library that would provide an optimal way
>    to parse from S the following
>  {'latitude':"",'longitude':""}
>  ?

import re
match = re.match('^Coordinates: (.+), (.+)$', S)
if match:
    data = {'latitude': match.group(1), 'longitude': match.group(2)}

Or you could use string methods and slicing to extract the figures,
which would be faster than the regular expression machinery.



More information about the Python-list mailing list