Reverse string-formatting (maybe?)

Tim Chase python.list at tim.thechases.com
Sat Oct 14 09:20:32 EDT 2006


>>>> template = 'I am %s, and he %s last %s.'
>>>> values = ('coding', "coded', 'week')
>>>> formatted = template % values
>>>> formatted
> 'I am coding, and he coded last week.'
>>>> deformat(formatted, template)
> ('coding', 'coded', 'week')
> 
> expanded (for better visual):
>>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last %s.')
> ('coding', 'coded', 'week')
> 
> It would return a tuple of strings, since it has no way of telling what
> the original type of each item was.
> 
> Any input? I've looked through the documentation of the string module
> and re module, did a search of the documentation and a search of this
> group, and come up empty-handed.


Yes, in the trivial case you provide, it can be done fairly 
easily using the re module:

 >>> import re
 >>> template = 'I am %s, and he %s last %s.'
 >>> values = ('coding', 'coded', 'week')
 >>> formatted = template % values
 >>> unformat_re = re.escape(template).replace('%s', '(.*)')
 >>> # unformat_re = unformat_re.replace('%i', '([0-9]+)')
 >>> r = re.compile(unformat_re)
 >>> r.match(formatted).groups()
('coding', 'coded', 'week')

Thing's get crazier when you have things like

 >>> answer ='format values into a string'
 >>> template = 'The formatting string %%s is used to %s' % answer

or

 >>> template = 'The value is %0*.*f'
 >>> values = (10, 4, 3.14159)
 >>> formatted = template % values
 >>> formated
'The value is 00003.1415'

or

 >>> template = 'Dear %(name)s, Thank you for the %(gift)s.  It 
was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj': 
'nice'}

Additionally, things go a little tangled when the replacement 
values duplicate matters in the template. Should the unformatting 
of "I am tired, and he didn't last last All Saint's Day" be 
parsed as ('tired', "didn't last", "All Saint's Day") or 
('tired', "didn't", "last All Saint's Day").  The /intent/ is 
likely the former, but getting a computer to understand intent is 
a non-trivial task ;)

Just a few early-morning thoughts...

-tkc









More information about the Python-list mailing list