python - Returning a Unicode string vs. Returning a normal string encoded as UTF-8? -
on tutorial page django web framework, author explains why adding __unicode__() method preferred __str__() following reason:
django models have default
__str__()method calls__unicode__(), converts result utf-8 bytestring. this meansunicode(p)return unicode string, ,str(p)return normal string, characters encoded utf-8.
i don't understand what's difference between unicode string , string characters encoded utf-8. thought utf-8 1 of encodings unicode?
python unicode objects abstract - represent sequence of unicode code points independent of particular encoding. utf-8 encoded string, on other hand, sequence of bytes encodes sequence of unicode code points. they're different levels of abstraction.
you can think of code points being abstract number, , encoding being particular binary representation of number. unicode object represents "number" (actually codepoints), while string represents binary. analogy not exact, if you're used idea that, say, object represent integer "8" different object represent specific bit sequence "00001000" may prove clarifying. if you've worked systems twos-complement, bit sequence represents abstract integer "8" different.
this essay, while ten years old, still 1 of clearest , comprehensive explanations of concepts i've ever run into.
this answer pretty on python-specific details.
Comments
Post a Comment