Reverse string-formatting (maybe?)

Dustan DustanGroups at gmail.com
Sun Oct 15 09:17:43 EDT 2006


Dustan wrote:
> Tim Chase wrote:
> > > 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?
> >
> > Given this new (key) information along with the assumption that
> > you're doing straight string replacement (not dictionary
> > replacement of the form "%(key)s" or other non-string types such
> > as "%05.2f"), then yes, a reversal is possible.  To make it more
> > explicit, one would do something like
> >
> >  >>> template = '%s, %s, %s'
> >  >>> values = ('Tom', 'Dick', 'Harry')
> >  >>> formatted = template % values
> >  >>> import re
> >  >>> unformat_string = template.replace('%s', '([^, ]+)')
> >  >>> unformatter = re.compile(unformat_string)
> >  >>> extracted_values = unformatter.search(formatted).groups()
> >
> > using '[^, ]+' to mean "one or more characters that aren't a
> > comma or a space".
> >
> > -tkc
>
> Thanks.
>
> One more thing (I forgot to mention this other situation earlier)
> The %s characters are ints, and outside can be anything except int
> characters. I do have one situation of '%s%s%s', but I can change it to
> '%s', and change the output into the needed output, so that's not
> important. Think something along the lines of "abckdaldj iweo%s
> qwierxcnv !%sjd".

That was written in haste. All the information is true. The question:
I've already created a function to do this, using your original
deformat function. Is there any way in which it might go wrong?




More information about the Python-list mailing list