Determining a replacement dictionary from scratch
Dave Benjamin
ramen at lackingtalent.com
Sun Jan 18 14:34:07 EST 2004
In article <4b805376.0401181116.3b0adb41 at posting.google.com>, Dan wrote:
> I'd like to be able to take a formatted string and determine the
> replacement dictionary necessary to do string interpolation with it.
> For example:
>
>>>> str = 'his name was %(name)s and i saw him %(years)s ago.'
>>>> createdict( str )
> {'name':'', 'years':''}
>>>>
>
> Notice how it would automatically fill in default values based on
> type. I figure since python does this automatically maybe there is a
> clever way to solve the problem. Otherwise I will just have to parse
> the string myself. Any clever solutions to this?
Here's a solution that uses a regular expression. It only handles strings
and doesn't cache the regular expression; I'll leave this up to you. =)
import re
def createdict(fmt):
keys = re.findall('%\(([A-Za-z]+)\)s', fmt)
return dict(zip(keys, [''] * len(keys)))
The regular expression works like this:
%\( - match a percent character and opening parenthesis
([A-Za-z]+) - match a sequence of one or more alpha characters as a GROUP
\)s - match a closing parenthesis and 's' character
For more details on "re", see the documentation:
http://python.org/doc/current/lib/module-re.html
HTH,
Dave
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
More information about the Python-list
mailing list