scanf style parsing

Skip Montanaro skip at
Wed Sep 26 08:14:58 CEST 2001

    Bruce> I want to find out how many errors and warnings there were:

    Bruce> smtpmail.exe - 0 error(s), 0 warning(s)

    Bruce> In C/C++ that would be something like:
    Bruce> sscanf(buffer, "smtpmail.exe - %d error(s), %d warning(s)", &errors,
    Bruce> &warnings);

    Bruce> It's not that I think the sscanf syntax is particularly elegant,
    Bruce> but it sure is compact! I saw the discussion about adding scanf
    Bruce> to Python

    Bruce> but I need to know what people do right now when faced with this
    Bruce> task.

This is a task often relegated to regular expressions, which probably
explains (in part) why scanf is not found in python.  You could define a
regular expression like

    errpat = re.compile(r'(?P<exe>[^\s]+)\s+-\s+'

then use it to extract the program name, number of errors and number of
warnings like so:

    mat = errpat.match(line)
    if mat is not None:
        exe ='exe')
        nerrs = int('err')
        nwarns = int('warn')

It's not nearly as compact as a similar scanf pattern, but regular
expressions are considerably more powerful.


Skip Montanaro (skip at

More information about the Python-list mailing list