【发布时间】:2013-09-27 00:14:41
【问题描述】:
我对编程还很陌生。我正在尝试编写两个将采用字符串的类方法, '{{name}} is in {{course}}' ,并将 {{name}} 和 {{course}} 替换为它们各自的 Key 值字典。所以:
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410'
}
out = t.process('{{name}} is in {{course}}', vars)
print 'out is: [' + out + ']'
将打印:
Jane is in CS 1410
我的代码如下:
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 + ']'
当我运行代码时,我得到以下输出:
{{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
我只是不明白如果模板是“{{course}}”,为什么我会收到断言错误 编辑: 以这种方式编写代码的目的是引入任何字典和字符串,以便我可以创建一个简单的社交网络。否则,更简单的方法将是熟练的。
【问题讨论】:
-
你知道你已经可以在 Python 中做到这一点了吗?
name = 'Pat'; print '%(name)s' % locals() -
@Paco 或只是
"{name} is in {course}".format(vars) -
其实是
'{name} is in {course}'.format(**vars)(别忘了**) -
@Paco 是的...但是我将在一个简单的社交网络的 Web 程序中使用这个类。所以代码甚至不知道字符串是什么,更不用说变量了。抱歉,我将进行编辑,以便我的代码的目的更明确。
标签: python assertions