Reverse string-formatting (maybe?)

Dustan DustanGroups at gmail.com
Sun Oct 15 08:42:55 EDT 2006


Peter Otten wrote:
> 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

Trying to figure out the 'unreliable' part of your statement...

I'm sure 2 '%s' characters in a row would be a bad idea, and if you
have similar expressions for the '%s' characters within as well as in
the neighborhood of the '%s', that would cause difficulty. Is there any
other reason it might not work properly?

My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?




More information about the Python-list mailing list