Page 1 of 1

Following extract function

Posted: Tue Mar 11, 2014 4:40 pm
by lilzz

Code: Select all

def extract(self, fmtArray, pathArray, args):
        if len(fmtArray) != len(pathArray):
            return False
        if len(fmtArray) == 0:
            return True
        fmt = fmtArray[0]
        path = pathArray[0]
        if fmt == path:
            return self.extract(fmtArray[1:], pathArray[1:], args)
        if fmt.startswith("%"):
            
            fmt = fmt[1:]
            t = 's'
            if fmt[0] == '(':
                if fmt[-1] == ')':
                    name = fmt[1:-1]
                elif fmt[-2] == ')':                                   
                    name = fmt[1:-2]
                    t = fmt[-1]
                else:
                    raise Exception("Missing closing brace")
            else:
                name = fmt
            
            if t == 's':
                args[name] = path
            elif t == 'b':
                args[name] = types.str2bool(path)
            elif t == 'd':
                args[name] = types.toint(path)
            elif t == 'x':
                args[name] = int(path, 16)
            elif t == 'f':
                args[name] = float(path)
            else:
                raise Exception("Unknown format type : %s" % t)
            
            return self.extract(fmtArray[1:], pathArray[1:], args)
            
        return False

I couldn't understand what the above function does. Anyone has some insight and give example?
what's pathArray[1:] versus pathArray[1:-1]?

Re: Following extract function

Posted: Tue Mar 11, 2014 5:41 pm
by elParaguayo
pathArray[1:] pathArray[1:-1] could be examples of string slicing.

for example:

Code: Select all

a="HELLO"
print a[1:] # prints "ELLO"
print a[1:-1] # prints "ELL"
The number before the ":" is the start position (remember it's a zero index so "H" would be a[0]). The number after the colon is the end position. Negative numbers can be used to count backwards from the end of the string.

If the objects are lists, then it works in a similar way.

Code: Select all

a=[1,2,3,4,5]
print a[1:] # prints [2,3,4,5]
print a[1:-1] # prints [2,3,4]