Reverse string-formatting (maybe?)

Dustan DustanGroups at
Sun Oct 15 15:15:00 CEST 2006

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 =
> using '[^, ]+' to mean "one or more characters that aren't a
> comma or a space".
> -tkc


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".

More information about the Python-list mailing list