Enumerating formatting strings

Michael Spencer mahs at telcopartners.com
Mon Apr 18 19:13:22 EDT 2005


Steve Holden wrote:

> I've been wondering whether it's possible to perform a similar analysis 
> on non-mapping-type format strings, so as to know how long a tuple to 
> provide, or whether I'd be forced to lexical analysis of the form string.
> 
> regards
>  Steve
I do not know if it is possible to do that.

But if you are forced to parse the string, the following might help:

import re
parse_format = re.compile(r'''
     \%                                  # placeholder
     (?P<name>\([\w]+\))?                # 0 or 1 named groups
     (?P<conversion>[\#0\-\+]?)          # 0 or 1 conversion flags
     (?P<width>[\d]* | \*)               # optional minimum conversion width
     (?:.(?P<precision>[\d]+ | \*))?     # optional precision
     (?P<lengthmodifier>[hlL]?)          # optional length modifier
     (?P<type>[diouxXeEfFgGcrs]{1})      # conversion type - note %% omitted
     ''',
     re.VERBOSE
     )


  >>> parse_format.findall("%(name)s, %-4.2f, %d, %%")
  [('(name)', '', '', '', '', 's'), ('', '-', '4', '2', '', 'f'), ('', '', '', 
'', '', 'd')]
  >>>

I used this successfully in a few simple cases, but I haven't really tested it.

cheers
Michael




More information about the Python-list mailing list