Skip to content

Instantly share code, notes, and snippets.

@tgarc
Last active July 21, 2016 15:50
Show Gist options
  • Save tgarc/b4cc7da45f18cff0006a36685f3b222a to your computer and use it in GitHub Desktop.
Save tgarc/b4cc7da45f18cff0006a36685f3b222a to your computer and use it in GitHub Desktop.
Parse the format specification (https://docs.python.org/2.7/library/string.html#format-specification-mini-language) from a .format style python string
import re
from string import Formatter
_fspecre = ("((?P<fill>{fill})?(?P<align>{align}))?"
"(?P<sign>{sign})?"
"(?P<prefix>#)?"
"(?P<zeropad>0)?"
"(?P<width>{width})?"
"(?P<thousands>,)?"
"(?:\.(?P<precision>{precision}))?"
"(?P<type>{type})?")
_fspecre = _fspecre.format( fill='.',
align="<|>|=|^",
sign="\+|-| ",
width="[0-9]+",
precision="[0-9]+",
type=r"b|c|d|e|E|f|F|g|G|n|o|s|x|X|%")
_fspecre = re.compile(_fspecre)
_format = Formatter()
def parse(fmt):
parsed = list(_format.parse(fmt))
if len(parsed) == 1:
parsed = [parsed]
for lit, fieldname, fspec, conv in parsed:
if fspec is not None:
fspec = _fspecre.match(fspec).groupdict()
yield lit, fieldname, fspec, conv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment