Reverse string-formatting (maybe?)

Tim Chase python.list at tim.thechases.com
Sun Oct 15 08:59:41 EDT 2006


> 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







More information about the Python-list mailing list