The string module has a Template class, that lets you make substitutions in a string using a mapping object, for instance:
>>>
This is a Quick Fix (Using recursion):
def check_substitution(tem, m):
try:
string.Template(tem).substitute(m)
except KeyError:
return False
except ValueError:
return check_substitution(tem.replace('$ ', '$'), m) #strip spaces after $
return True
I Know its take a longer time if there is more than One Space between $ and var , so you may improve it by using Regular Expression.
EDIT
escaping $ into $$ makes more sense [ Thanks @Pedro ] so you can catch ValueError by this statement:
return check_substitution(tem.replace('$ ', '$$ '), m) #escaping $ by $$