I'm fairly new to programming. I'm trying to write two class methods that will take a string, '{{name}} is in {{course}}' , and replace {{name}} and {{course}} with their respective Key values in a dictionary. So:
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410'
}
out = t.process('{{name}} is in {{course}}', vars)
print 'out is: [' + out + ']'
Would print:
Jane is in CS 1410
My code goes as:
class Template:
def processVariable(self, template, data):
print template
assert(template.startswith('{{'))
start = template.find("{{")
end = template.find("}}")
out = template[start+2:end]
assert(out != None)
assert(out in data)
return data[out]
def process(self, template, data):
output = ""
check = True
while check == True:
start = template.find("{{")
end = template.find("}}")
output += template[:start]
output += self.processVariable(template[start:end+2], data)
template = template.replace(template[:end+2], "")
for i in template:
if i == "}}":
check = True
output += template
return output
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410'
}
out = t.process('{{name}} is in {{course}}', vars)
print 'out is: [' + out + ']'
When I run the code, I get the following output:
{{name}}
{{course}}
Traceback (most recent call last):
File "C:some/filepath/name.py", line 46, in <module>
out = t.process('{{name}} is in {{course}}', vars)
File "C:some/filepath/name.py", line 28, in process
output += self.processVariable(template[start:end+2], data)
File "C:some/filepath/name.py", line 8, in processVariable
assert(template.startswith('{{'))
AssertionError
I just don't understand why im getting that assertion error if template is '{{course}}'
Edit:
The purpose making the code this way, was to bring in any dictionary and string, so that I can create a simple social network. Otherwise much simpler methods would be proficient.