substitute variables in a string

def substitute(self, text, subvars={},
                   checkmissing=None):
        '''substitute variables in a string'''

        if checkmissing is None:
            checkmissing = self.checkmissing

        while True:
            idx = text.find(self.start_var_token)
            if idx == -1:
                return text
            endidx = text[idx:].find(self.end_var_token)
            if endidx == -1:
                raise MAVSubstituteError('missing end of variable: %s' % text[idx:idx+10])
            varname = text[idx+2:idx+endidx]
            fullvar = varname

            # allow default value after a :
            def_value = None
            colon = varname.find(':')
            if colon != -1:
                def_value = varname[colon+1:]
                varname = varname[:colon]

            if varname in subvars:
                value = subvars[varname]
            elif def_value is not None:
                value = def_value
            elif checkmissing:
                raise MAVSubstituteError("unknown variable in '%s%s%s'" % (
                    self.start_var_token, varname, self.end_var_token))
            else:
                return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, checkmissing=False)
            text = text.replace("%s%s%s" % (self.start_var_token, fullvar, self.end_var_token), str(value))
        return text