Context Rendering in Django

北战南征 提交于 2020-01-04 14:13:29

问题


I am new in django.So while i was practising django template in shell i saw two different output of "render()" .So here it goes.

from django.template import Template,Context
t = Template("My name is {{name}}.")
c = Context("name":"sraban")
t.render(c)

So while i hit enter in shell it shows

u'My name is sraban'

But while i wrote

from django.template import Template,Context
t = Template("My name is {{name}}.")
c = Context("name":"sraban")
print t.render(c)

It's output is

My name is sraban

So I want to know what is that extra "u" in the first output and why two output varies??? I use django1.6 in python 2.7.3 .


回答1:


The u means the string is a unicode string. This is called a string prefix. The reason it appears in the first example is that the default way to represent a value in the interactive shell is to use the value the function repr returns when called with that value as argument. The second example is missing the prefix because print doesn't use the repr-representation for strings, but their actual value.




回答2:


Complementing kroolik answer:

If you take a look closer you will notice that the u is not the unique difference, in the second output there is no ' characters.

The difference has to do with the use of two different functions: repr and str-- as kroolik pointed out-- you can read about them here: Input and Output

Taken from Python Doc.

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr().

So, that's why you see the 'u' the interpreter needs to know if a string is unicode or not and thats the way it does it.

At this point it must be obviuos to you that the function: Template.render use the repr() function while print doesn't.



来源:https://stackoverflow.com/questions/25750739/context-rendering-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!