Unicode for dummies — Python Encoding
Join the DZone community and get the full member experience.Join For Free
another entry in an irregular series of posts about unicode .
this is a story about encoding and decoding, with a minor subplot involving unicode.
as our story begins — on a dark and stormy night, of course — we find
our protagonist deep in thought. he is asking himself “what is an
what is an encoding?
the basic concepts are simple. first, we start with the idea of a piece of information — a message — that exists in a representation that is understandable (perspicuous) to a human being. i’m going to call that representation “plain text”. for english-language speakers, for example, english words printed on a page, or displayed on a screen, count as plain text.
next, (for reasons that we won’t explore right now) we need to be
able to translate a message in a plain-text representation into some
other representation (let’s call that representation the “encoded
text”), and we need to be able to translate the encoded text back into
plain text. the translation from plain text to encoded text is called
“encoding”, and the translation of encoded text back into plain text is
there are three points worth noting about this process.
the first point is that no information can be lost during encoding or decoding. it must be possible for us to send a message on a round-trip journey — from plain text to encoded text, and then back again from encoded text to plain text — and get back exactly the same plain text that we started with. that is why, for instance, we can’t use one natural language (russian, chinese, french, navaho) as an encoding for another natural language (english, hindi, swahili). the mappings between natural languages are too loose to guarantee that a piece of information can make the round-trip without losing something in translation.
the requirement for a lossless round-trip means that the mapping between the plain text and the encoded text must be very tight, very exact. and that brings us to the second point .
in order for the mapping between the plain text and the encoded text to be very tight — which is to say: in order for us to be able to specify very precisely how the encoding and decoding processes work — we must specify very precisely what the plain text representation looks like.
suppose, for example, we say that plain text looks like this: the 26 upper-case letters of the anglo-american alphabet, plus the space and three punctuation symbols: period (full stop), question mark, and dash (hyphen). this gives us a plain-text alphabet of 30 characters. if we need numbers, we can spell them out, like this: “six thousand seven hundred forty-three”.
on the other hand, we may wish to say that our plain text looks like this: 26 upper-case letters, 26 lower-case letters, 10 numeric digits, the space character, and a dozen types of punctuation marks: period, comma, double-quote, left parenthesis, right parenthesis, and so on. that gives us a plain-text alphabet of 75 characters.
once we’ve specified exactly what a plain-text representation of a
message looks like — a finite sequence of characters from our
30-character alphabet, or perhaps our 75-character alphabet — then we
can devise a system (a code) that can reliably encode and decode
plain-text messages written in that alphabet. the simplest such system
is one in which every character in the plain-text alphabet has one and
only one corresponding representation in the encoded text. a familiar
example is morse code, in which “sos” in plain text corresponds to
... --- ...
in encoded text.
in the real world, of course, the selection of characters for the plain-text alphabet is influenced by technological limitations on the encoded text. suppose we have several available technologies for storing encoded messages: one technology supports an encoded alphabet of 256 characters, another technology supports only 128 encoded characters, and a third technology supports only 64 encoded characters. naturally, we can make our plain-text alphabet much larger if we know that we can use a technology that supports a larger encoded-text alphabet.
and the reverse is also true. if we know that our plain-text alphabet must be very large, then we know that we must find — or devise — a technology capable of storing a large number of encoded characters.
which brings us to unicode.
unicode was devised to be a system capable of storing encoded representations of every plain-text character of every human language that has ever existed. english, french, spanish. greek. arabic. hindi. chinese. assyrian (cuneiform characters).
that’s a lot of characters.
so the first task of the unicode initiative was simply to list all of those characters, and count them. that’s the first half of unicode, the universal character set . (and if you really want to “talk unicode”, don’t call plain-text characters “characters”. call them “code points”.)
once you’ve done that, you’ve got to figure out a technology for storing all of the corresponding encoded-text characters. (in unicode-speak, the encoded-text characters are called “code values”.)
in fact unicode defines not one but several methods of mapping code points to code values. each of these methods has its own name. some of the names start with “utf”, others start with “ucs”: utf-8, utf-16, utf-32, ucs-2, ucs-4, and so on. the naming convention is “utf-<number of bits in a code value>” and “ucs-<number of byes in a code value>” some (e.g. ucs-4 and utf-32) are functionally equivalent. see the wikipedia article on unicode .
the most important thing about these methods is that some are fixed-width encodings and some are variable-width encodings. the basic idea is that the fixed-width encodings are very long — ucs-4 and utf-32 are 4 bytes (32 bits) long — long enough to hold the the biggest code value that we will ever need.
in contrast, the variable-width encodings are designed to be short,
but expandable. utf-8, for example, can use as few as 8 bits (one byte)
to store latin and ascii
code points. but it
also has a sort of “continued on the next byte” mechanism that allows it
to use 2 bytes or even 4 bytes if it needs to (as it might, for chinese
characters). for western programmers, that means that utf-8 is both
efficient and flexible, which is why utf-8 is the de facto standardard
encoding for exchanging unicode text.
there is, then, no such thing as the unicode encoding system or method. there are several encoding methods, and if you want to exchange text with someone, you need explicitly to specify which encoding method you are using.
is it, say, this.
or something else.
which brings us back to something i said earlier.
why encode something in unicode?
at the beginning of this post i said
we start with the idea of a piece of information — a message — that exists in a representation that is understandable (perspicuous) to a human being.
next, (for reasons that we won’t explore right now) we need to be able to translate a message in a plain-text representation into some other representation. the translation from plain text to encoded text is called “encoding”, and the translation of encoded text back into plain text is called “decoding”.
ok. so now it is time to explore those reasons. why might we want to translate a message in a plain-text representation into some other representation?
one reason, of course, is that we want to keep a secret. we want to hide the plain text of our message by encrypting and decrypting it — basically, by keeping the algorithms for encoding and decoding secret and private.
but that is a completely different subject. right now, we’re not
interested in keeping secrets; we’re python programmers and we’re
interested in unicode. so:
why — as a python programmer — would i need to be able to translate a plain-text message into some encoded representation… say, a unicode representation such as utf-8?
suppose you are happily sitting at your pc, working with your favorite text editor, writing the standard hello world program in python (specifically, in python 3+). this single line is your entire program.
here, “hello, world!” is plain text. you can see it on your screen. you can read it. you know what it means. it is just a string and you can (if you wish) do standard string-type operations on it, such as taking a substring (a slice).
but now suppose you want to put this string — “hello, world!” — into a file and save the file on your hard drive. perhaps you plan to send the file to a friend.
that means that you must eject your poor little string from the warm, friendly, protected home in your python program, where it exists simply as plain-text characters. you must thrust it into the cold, impersonal, outside world of the file system. and out there it will exist not as characters, but as mere 1′s and 0′s, a jumble of dits and dots, charged and uncharged particles. and that means that your happy little plain-text string must be represented by some specific configuration of 1s and 0s , so that when somebody wants to retrieve that collection of 1s and 0s and convert it back into readable plain text, they can.
the process of converting a plain text into a specific configuration of 1s and 0s is a process of encoding . in order to write a string to a file, you must encode it using some encoding system (such as utf-8). and to get it back from a file, you must read the file and decode the collection of 1s and 0s back into plain text.
the need to encode/decode strings when writing/reading them from/to files isn’t something new — it is not an additional burden imposed by python 3′s new support for unicode. it is something you have always done. but it wasn’t always so obvious. in earlier versions of python, the encoding scheme was ascii . and because, in those olden times, ascii was pretty much the only game in town, you didn’t need to specify that you wanted to write and read your files in ascii. python just assumed it by default and did it. but — whether or not you realized it — whenever one of your programs wrote or read strings from a file, python was busy behind the scene, doing the encoding and decoding for you.
so that’s why you — as a python programmer — need to be able to
encode and decode text into, and out of, utf-8 (or some other encoding:
utf-16, ascii, whatever). you need to encode your strings as 1s and 0s
so you can put those 1s and 0s into a file and send the file to someone
what is plain text?
earlier, i said that there were three points worth noting about the encoding/decoding process, and i discussed the first two. here is the third point .
the distinction between plain text and encoded text is relative and context-dependent.
as programmers, we think of plain text as being written text. but it is possible to look at matters differently. for instance, we can think of spoken text as the plain text, and written text as the encoded text. from this perspective, writing is encoded speech. and there are many different encodings for speech as writing. think of egyptian hieroglyphics, mayan hieroglyphics, the latin alphabet, the greek alphabet, arabic, chinese ideograms, wonderfully flowing devanagari देवनागरी , sharp pointy cuneiform wedges, even shorthand. these are all written encodings for the spoken word. they are all, as thomas hobbes put it, “marks by which we may remember our thoughts”.
which reminds us that, in a different context, even speech itself — language — may be regarded as a form of encoding. in much of early modern philosophy (think of hobbes and locke) speech (or language) was basically considered to be an encoding of thoughts and ideas. communication happens when i encode my thought into language and say something — speak to you. you hear the sound of my words and decode it back into ideas. we achieve communication when i successfully transmit a thought from my mind to your mind via language. you understand me when — as a result of my speech — you have the same idea in your mind as i have in mine. (see ian hacking, why does language matter to philosophy? )
finally, note that in other contexts, the “plain text” isn’t even text. where the plain text is soundwaves (e.g. music), it can be encoded as an mp3 file. where the plain text is an image, it can be encoded as a gif, or png, or jpg file. where the plain text is a movie, it can be encoded as a wmv file. and so on.
everywhere, we are surrounded by encoding and decoding.
think of it this way: a string is an abstract representation of text. a string consists of characters, which are also abstract entities not tied to any particular binary representation. when manipulating strings, we’re living in blissful ignorance. we can split and slice them, concatenate and search inside them. we don’t care how they are represented internally and how many bytes it takes to hold each character in them. we only start caring about this when encoding strings into bytes (for example, in order to send them over a communication channel), or decoding strings from bytes (for the other direction).
i strongly recommend charles petzold’s wonderful book code: the hidden language of computer hardware and software.
and finally, i’ve found stephen pincock’s codebreaker: the history of secret communications a delightful read. it will tell you, among many other things, how the famous wwii navaho codetalkers could talk about submarines and dive bombers… despite the fact that there are no navaho words for “submarine” or “dive bomber”.
Opinions expressed by DZone contributors are their own.