def contextualize_text(text, context):
 if (not text):
  return text
 for key in sorted(context, (lambda x, y: cmp(len(y), len(x)))):
  if (('$' + key) in text):
   try:
    s = str(context[key])
   except UnicodeEncodeError:
    s = context[key].encode('utf8', errors='ignore')
   text = text.replace(('$' + key), s)
 return text

def contextualize_text ( text , context ) : if ( not text ) : return text for key in sorted ( context , ( lambda x , y : cmp ( len ( y ) , len ( x ) ) ) ) : if ( ( '$' + key ) in text ) : try : s = str ( context [ key ] ) except UnicodeEncodeError : s = context [ key ] . encode ( 'utf8' , errors = 'ignore' ) text = text . replace ( ( '$' + key ) , s ) return text
takes a string with variables .