Reputation: 21
I know this question has been asked before but I can't seem to get mine working. Can someone help me out with this?
import sys
class Template:
def processVariable(self, template, data):
first = template.find('{{')
second = template.find('}}')
second = second + 2
out = template[first+second]
assert[out.startswith('{{')]
out = out.strip('{}')
rest = template[second:]
if out in data:
newstring = data[out]
return(rest, newstring)
else:
print "Invalid Data Passed it"
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410',
'adjective': 'shimmering'
}
(rest, out) = t.processVariable('{{name}} is in {{course}}', vars)
This is the error I am getting:
File "template.py", line 28, in <module>
(rest, out) = t.processVariable('{{name}} is in {{course}}', vars)
TypeError: 'NoneType' object is not iterable
I understand the NoneType but is it because of my for loop or did I just miss something simple? Thanks in advance!
My code will be passed into a field so that my teacher can run a code against it and it will pass or fail. This is what his code will run:
import Candidate
t = Candidate.Template()
vars = {
'name': 'Jane',
'course': 'CS 1410',
'adjective': 'shimmering'
}
(rest, out) = t.processVariable('{{course}} is {{adjective}}', vars)
print 'rest is: [' + rest + ']'
print 'out is : [' + out + ']
what it should return is:
rest is: [ is in {{course}}]
out is : [Jane]
it will return Yes or No if it worked.
Upvotes: 1
Views: 23677
Reputation: 177461
There are errors in your code.
This:
out = template[first+second]
assert[out.startswith('{{')]
Should be:
out = template[first:second]
assert out.startswith('{{')
And:
else:
print "Invalid Data Passed it"
Should probably be:
else:
raise ValueError('Invalid data')
Also this functionality is already in Python:
from string import Template
t = Template('$name is in $course')
vars = {
'name': 'Jane',
'course': 'CS 1410',
'adjective': 'shimmering'
}
print(t.substitute(vars))
Output:
Jane is in CS 1410
Upvotes: 3
Reputation: 213193
You didn't return anything from your else
part, and hence your function will by default return None
.
Ad of course, you cannot unpack a None
into two variables. Try returning a tuple from your else part like this:
if out in data:
newstring = data[out]
return (rest, newstring)
else:
print "Invalid Data Passed it"
return (None, None)
Upvotes: 5