Reverse string-formatting (maybe?)

Peter Otten __peter__ at web.de
Sat Oct 14 09:26:37 EDT 2006


Dustan wrote:

> Is there any builtin function or module with a function similar to my
> made-up, not-written deformat function as follows? I can't imagine it
> would be too easy to write, but possible...
> 
>>>> 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.

Simple, but unreliable:

>>> import re
>>> template = "I am %s, and he %s last %s."
>>> values = ("coding", "coded", "week")
>>> formatted = template % values
>>> def deformat(formatted, template):
...     r = re.compile("(.*)".join(template.split("%s")))
...     return r.match(formatted).groups()
...
>>> deformat(formatted, template)
('coding', 'coded', 'week')

Peter



More information about the Python-list mailing list