blob: 40c77d6453edf5ddf0845d03c230cb7be5228bd0 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001*****************
2 Unicode HOWTO
3*****************
4
5:Release: 1.02
6
7This HOWTO discusses Python's support for Unicode, and explains various problems
8that people commonly encounter when trying to work with Unicode.
9
Georg Brandl6911e3c2007-09-04 07:15:32 +000010.. XXX fix it
11.. warning::
12
13 This HOWTO has not yet been updated for Python 3000's string object changes.
14
15
Georg Brandl116aa622007-08-15 14:28:22 +000016Introduction to Unicode
17=======================
18
19History of Character Codes
20--------------------------
21
22In 1968, the American Standard Code for Information Interchange, better known by
23its acronym ASCII, was standardized. ASCII defined numeric codes for various
24characters, with the numeric values running from 0 to
25127. For example, the lowercase letter 'a' is assigned 97 as its code
26value.
27
28ASCII was an American-developed standard, so it only defined unaccented
29characters. There was an 'e', but no 'é' or 'Í'. This meant that languages
30which required accented characters couldn't be faithfully represented in ASCII.
31(Actually the missing accents matter for English, too, which contains words such
32as 'naïve' and 'café', and some publications have house styles which require
33spellings such as 'coöperate'.)
34
35For a while people just wrote programs that didn't display accents. I remember
36looking at Apple ][ BASIC programs, published in French-language publications in
37the mid-1980s, that had lines like these::
38
39 PRINT "FICHER EST COMPLETE."
40 PRINT "CARACTERE NON ACCEPTE."
41
42Those messages should contain accents, and they just look wrong to someone who
43can read French.
44
45In the 1980s, almost all personal computers were 8-bit, meaning that bytes could
46hold values ranging from 0 to 255. ASCII codes only went up to 127, so some
47machines assigned values between 128 and 255 to accented characters. Different
48machines had different codes, however, which led to problems exchanging files.
49Eventually various commonly used sets of values for the 128-255 range emerged.
50Some were true standards, defined by the International Standards Organization,
51and some were **de facto** conventions that were invented by one company or
52another and managed to catch on.
53
54255 characters aren't very many. For example, you can't fit both the accented
55characters used in Western Europe and the Cyrillic alphabet used for Russian
56into the 128-255 range because there are more than 127 such characters.
57
58You could write files using different codes (all your Russian files in a coding
59system called KOI8, all your French files in a different coding system called
60Latin1), but what if you wanted to write a French document that quotes some
61Russian text? In the 1980s people began to want to solve this problem, and the
62Unicode standardization effort began.
63
64Unicode started out using 16-bit characters instead of 8-bit characters. 16
65bits means you have 2^16 = 65,536 distinct values available, making it possible
66to represent many different characters from many different alphabets; an initial
67goal was to have Unicode contain the alphabets for every single human language.
68It turns out that even 16 bits isn't enough to meet that goal, and the modern
69Unicode specification uses a wider range of codes, 0-1,114,111 (0x10ffff in
70base-16).
71
72There's a related ISO standard, ISO 10646. Unicode and ISO 10646 were
73originally separate efforts, but the specifications were merged with the 1.1
74revision of Unicode.
75
76(This discussion of Unicode's history is highly simplified. I don't think the
77average Python programmer needs to worry about the historical details; consult
78the Unicode consortium site listed in the References for more information.)
79
80
81Definitions
82-----------
83
84A **character** is the smallest possible component of a text. 'A', 'B', 'C',
85etc., are all different characters. So are 'È' and 'Í'. Characters are
86abstractions, and vary depending on the language or context you're talking
87about. For example, the symbol for ohms (Ω) is usually drawn much like the
88capital letter omega (Ω) in the Greek alphabet (they may even be the same in
89some fonts), but these are two different characters that have different
90meanings.
91
92The Unicode standard describes how characters are represented by **code
93points**. A code point is an integer value, usually denoted in base 16. In the
94standard, a code point is written using the notation U+12ca to mean the
95character with value 0x12ca (4810 decimal). The Unicode standard contains a lot
96of tables listing characters and their corresponding code points::
97
98 0061 'a'; LATIN SMALL LETTER A
99 0062 'b'; LATIN SMALL LETTER B
100 0063 'c'; LATIN SMALL LETTER C
101 ...
102 007B '{'; LEFT CURLY BRACKET
103
104Strictly, these definitions imply that it's meaningless to say 'this is
105character U+12ca'. U+12ca is a code point, which represents some particular
106character; in this case, it represents the character 'ETHIOPIC SYLLABLE WI'. In
107informal contexts, this distinction between code points and characters will
108sometimes be forgotten.
109
110A character is represented on a screen or on paper by a set of graphical
111elements that's called a **glyph**. The glyph for an uppercase A, for example,
112is two diagonal strokes and a horizontal stroke, though the exact details will
113depend on the font being used. Most Python code doesn't need to worry about
114glyphs; figuring out the correct glyph to display is generally the job of a GUI
115toolkit or a terminal's font renderer.
116
117
118Encodings
119---------
120
121To summarize the previous section: a Unicode string is a sequence of code
122points, which are numbers from 0 to 0x10ffff. This sequence needs to be
123represented as a set of bytes (meaning, values from 0-255) in memory. The rules
124for translating a Unicode string into a sequence of bytes are called an
125**encoding**.
126
127The first encoding you might think of is an array of 32-bit integers. In this
128representation, the string "Python" would look like this::
129
130 P y t h o n
Georg Brandl6911e3c2007-09-04 07:15:32 +0000131 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
132 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134This representation is straightforward but using it presents a number of
135problems.
136
1371. It's not portable; different processors order the bytes differently.
138
1392. It's very wasteful of space. In most texts, the majority of the code points
140 are less than 127, or less than 255, so a lot of space is occupied by zero
141 bytes. The above string takes 24 bytes compared to the 6 bytes needed for an
142 ASCII representation. Increased RAM usage doesn't matter too much (desktop
143 computers have megabytes of RAM, and strings aren't usually that large), but
144 expanding our usage of disk and network bandwidth by a factor of 4 is
145 intolerable.
146
1473. It's not compatible with existing C functions such as ``strlen()``, so a new
148 family of wide string functions would need to be used.
149
1504. Many Internet standards are defined in terms of textual data, and can't
151 handle content with embedded zero bytes.
152
153Generally people don't use this encoding, instead choosing other encodings that
154are more efficient and convenient.
155
156Encodings don't have to handle every possible Unicode character, and most
157encodings don't. For example, Python's default encoding is the 'ascii'
158encoding. The rules for converting a Unicode string into the ASCII encoding are
159simple; for each code point:
160
1611. If the code point is < 128, each byte is the same as the value of the code
162 point.
163
1642. If the code point is 128 or greater, the Unicode string can't be represented
165 in this encoding. (Python raises a :exc:`UnicodeEncodeError` exception in this
166 case.)
167
168Latin-1, also known as ISO-8859-1, is a similar encoding. Unicode code points
1690-255 are identical to the Latin-1 values, so converting to this encoding simply
170requires converting code points to byte values; if a code point larger than 255
171is encountered, the string can't be encoded into Latin-1.
172
173Encodings don't have to be simple one-to-one mappings like Latin-1. Consider
174IBM's EBCDIC, which was used on IBM mainframes. Letter values weren't in one
175block: 'a' through 'i' had values from 129 to 137, but 'j' through 'r' were 145
176through 153. If you wanted to use EBCDIC as an encoding, you'd probably use
177some sort of lookup table to perform the conversion, but this is largely an
178internal detail.
179
180UTF-8 is one of the most commonly used encodings. UTF stands for "Unicode
181Transformation Format", and the '8' means that 8-bit numbers are used in the
182encoding. (There's also a UTF-16 encoding, but it's less frequently used than
183UTF-8.) UTF-8 uses the following rules:
184
1851. If the code point is <128, it's represented by the corresponding byte value.
1862. If the code point is between 128 and 0x7ff, it's turned into two byte values
187 between 128 and 255.
1883. Code points >0x7ff are turned into three- or four-byte sequences, where each
189 byte of the sequence is between 128 and 255.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000190
Georg Brandl116aa622007-08-15 14:28:22 +0000191UTF-8 has several convenient properties:
192
1931. It can handle any Unicode code point.
1942. A Unicode string is turned into a string of bytes containing no embedded zero
195 bytes. This avoids byte-ordering issues, and means UTF-8 strings can be
196 processed by C functions such as ``strcpy()`` and sent through protocols that
197 can't handle zero bytes.
1983. A string of ASCII text is also valid UTF-8 text.
1994. UTF-8 is fairly compact; the majority of code points are turned into two
200 bytes, and values less than 128 occupy only a single byte.
2015. If bytes are corrupted or lost, it's possible to determine the start of the
202 next UTF-8-encoded code point and resynchronize. It's also unlikely that
203 random 8-bit data will look like valid UTF-8.
204
205
206
207References
208----------
209
210The Unicode Consortium site at <http://www.unicode.org> has character charts, a
211glossary, and PDF versions of the Unicode specification. Be prepared for some
212difficult reading. <http://www.unicode.org/history/> is a chronology of the
213origin and development of Unicode.
214
215To help understand the standard, Jukka Korpela has written an introductory guide
216to reading the Unicode character tables, available at
217<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
218
219Roman Czyborra wrote another explanation of Unicode's basic principles; it's at
220<http://czyborra.com/unicode/characters.html>. Czyborra has written a number of
221other Unicode-related documentation, available from <http://www.cyzborra.com>.
222
223Two other good introductory articles were written by Joel Spolsky
224<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff
225<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make
226things clear to you, you should try reading one of these alternate articles
227before continuing.
228
229Wikipedia entries are often helpful; see the entries for "character encoding"
230<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
231<http://en.wikipedia.org/wiki/UTF-8>, for example.
232
233
234Python's Unicode Support
235========================
236
237Now that you've learned the rudiments of Unicode, we can look at Python's
238Unicode features.
239
Georg Brandlf6945182008-02-01 11:56:49 +0000240The String Type
241---------------
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandlf6945182008-02-01 11:56:49 +0000243Since Python 3.0, the language features a ``str`` type that contain Unicode
244characters, meaning any string created using ``"unicode rocks!"``, ``'unicode
245rocks!``, or the triple-quoted string syntax is stored as Unicode.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandlf6945182008-02-01 11:56:49 +0000247To insert a Unicode character that is not part ASCII, e.g., any letters with
248accents, one can use escape sequences in their string literals as such::
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandlf6945182008-02-01 11:56:49 +0000250 >>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name
251 '\u0394'
252 >>> "\u0394" # Using a 16-bit hex value
253 '\u0394'
254 >>> "\U00000394" # Using a 32-bit hex value
255 '\u0394'
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandlf6945182008-02-01 11:56:49 +0000257In addition, one can create a string using the :func:`decode` method of
258:class:`bytes`. This method takes an encoding, such as UTF-8, and, optionally,
259an *errors* argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandlf6945182008-02-01 11:56:49 +0000261The *errors* argument specifies the response when the input string can't be
Georg Brandl116aa622007-08-15 14:28:22 +0000262converted according to the encoding's rules. Legal values for this argument are
Georg Brandlf6945182008-02-01 11:56:49 +0000263'strict' (raise a :exc:`UnicodeDecodeError` exception), 'replace' (add U+FFFD,
Georg Brandl116aa622007-08-15 14:28:22 +0000264'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the
265Unicode result). The following examples show the differences::
266
Georg Brandlf6945182008-02-01 11:56:49 +0000267 >>> b'\x80abc'.decode("utf-8", "strict")
Georg Brandl116aa622007-08-15 14:28:22 +0000268 Traceback (most recent call last):
269 File "<stdin>", line 1, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000270 UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
Georg Brandl116aa622007-08-15 14:28:22 +0000271 ordinal not in range(128)
Georg Brandlf6945182008-02-01 11:56:49 +0000272 >>> b'\x80abc'.decode("utf-8", "replace")
273 '\ufffdabc'
274 >>> b'\x80abc'.decode("utf-8", "ignore")
275 'abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Georg Brandlf6945182008-02-01 11:56:49 +0000277Encodings are specified as strings containing the encoding's name. Python
Georg Brandl116aa622007-08-15 14:28:22 +0000278comes with roughly 100 different encodings; see the Python Library Reference at
279<http://docs.python.org/lib/standard-encodings.html> for a list. Some encodings
280have multiple names; for example, 'latin-1', 'iso_8859_1' and '8859' are all
281synonyms for the same encoding.
282
Georg Brandlf6945182008-02-01 11:56:49 +0000283One-character Unicode strings can also be created with the :func:`chr`
Georg Brandl116aa622007-08-15 14:28:22 +0000284built-in function, which takes integers and returns a Unicode string of length 1
285that contains the corresponding code point. The reverse operation is the
286built-in :func:`ord` function that takes a one-character Unicode string and
287returns the code point value::
288
Georg Brandlf6945182008-02-01 11:56:49 +0000289 >>> chr(40960)
290 '\ua000'
291 >>> ord('\ua000')
Georg Brandl116aa622007-08-15 14:28:22 +0000292 40960
293
Georg Brandlf6945182008-02-01 11:56:49 +0000294Converting to Bytes
295-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandlf6945182008-02-01 11:56:49 +0000297Another important str method is ``.encode([encoding], [errors='strict'])``,
298which returns a ``bytes`` representation of the Unicode string, encoded in the
299requested encoding. The ``errors`` parameter is the same as the parameter of
300the :meth:`decode` method, with one additional possibility; as well as 'strict',
Georg Brandl116aa622007-08-15 14:28:22 +0000301'ignore', and 'replace', you can also pass 'xmlcharrefreplace' which uses XML's
302character references. The following example shows the different results::
303
Georg Brandlf6945182008-02-01 11:56:49 +0000304 >>> u = chr(40960) + 'abcd' + chr(1972)
Georg Brandl116aa622007-08-15 14:28:22 +0000305 >>> u.encode('utf-8')
Georg Brandlf6945182008-02-01 11:56:49 +0000306 b'\xea\x80\x80abcd\xde\xb4'
Georg Brandl116aa622007-08-15 14:28:22 +0000307 >>> u.encode('ascii')
308 Traceback (most recent call last):
309 File "<stdin>", line 1, in ?
310 UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
311 >>> u.encode('ascii', 'ignore')
Georg Brandlf6945182008-02-01 11:56:49 +0000312 b'abcd'
Georg Brandl116aa622007-08-15 14:28:22 +0000313 >>> u.encode('ascii', 'replace')
Georg Brandlf6945182008-02-01 11:56:49 +0000314 b'?abcd?'
Georg Brandl116aa622007-08-15 14:28:22 +0000315 >>> u.encode('ascii', 'xmlcharrefreplace')
Georg Brandlf6945182008-02-01 11:56:49 +0000316 b'&#40960;abcd&#1972;'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000317
Georg Brandl116aa622007-08-15 14:28:22 +0000318The low-level routines for registering and accessing the available encodings are
319found in the :mod:`codecs` module. However, the encoding and decoding functions
320returned by this module are usually more low-level than is comfortable, so I'm
321not going to describe the :mod:`codecs` module here. If you need to implement a
322completely new encoding, you'll need to learn about the :mod:`codecs` module
323interfaces, but implementing encodings is a specialized task that also won't be
324covered here. Consult the Python documentation to learn more about this module.
325
326The most commonly used part of the :mod:`codecs` module is the
327:func:`codecs.open` function which will be discussed in the section on input and
328output.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000329
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331Unicode Literals in Python Source Code
332--------------------------------------
333
Georg Brandlf6945182008-02-01 11:56:49 +0000334In Python source code, specific Unicode code points can be written using the
335``\u`` escape sequence, which is followed by four hex digits giving the code
336point. The ``\U`` escape sequence is similar, but expects 8 hex digits, not 4::
Georg Brandl116aa622007-08-15 14:28:22 +0000337
Georg Brandlf6945182008-02-01 11:56:49 +0000338 >>> s = "a\xac\u1234\u20ac\U00008000"
339 ^^^^ two-digit hex escape
340 ^^^^^ four-digit Unicode escape
341 ^^^^^^^^^^ eight-digit Unicode escape
Georg Brandl6911e3c2007-09-04 07:15:32 +0000342 >>> for c in s: print(ord(c), end=" ")
343 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000344 97 172 4660 8364 32768
345
346Using escape sequences for code points greater than 127 is fine in small doses,
347but becomes an annoyance if you're using many accented characters, as you would
348in a program with messages in French or some other accent-using language. You
Georg Brandlf6945182008-02-01 11:56:49 +0000349can also assemble strings using the :func:`chr` built-in function, but this is
Georg Brandl116aa622007-08-15 14:28:22 +0000350even more tedious.
351
352Ideally, you'd want to be able to write literals in your language's natural
353encoding. You could then edit Python source code with your favorite editor
354which would display the accented characters naturally, and have the right
355characters used at runtime.
356
Georg Brandlf6945182008-02-01 11:56:49 +0000357Python supports writing Unicode literals in UTF-8 by default, but you can use
358(almost) any encoding if you declare the encoding being used. This is done by
359including a special comment as either the first or second line of the source
360file::
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 #!/usr/bin/env python
363 # -*- coding: latin-1 -*-
Georg Brandl6911e3c2007-09-04 07:15:32 +0000364
Georg Brandlf6945182008-02-01 11:56:49 +0000365 u = 'abcdé'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000366 print(ord(u[-1]))
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368The syntax is inspired by Emacs's notation for specifying variables local to a
369file. Emacs supports many different variables, but Python only supports
370'coding'. The ``-*-`` symbols indicate that the comment is special; within
371them, you must supply the name ``coding`` and the name of your chosen encoding,
372separated by ``':'``.
373
Georg Brandlf6945182008-02-01 11:56:49 +0000374If you don't include such a comment, the default encoding used will be UTF-8 as
375already mentioned.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000376
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378Unicode Properties
379------------------
380
381The Unicode specification includes a database of information about code points.
382For each code point that's defined, the information includes the character's
383name, its category, the numeric value if applicable (Unicode has characters
384representing the Roman numerals and fractions such as one-third and
385four-fifths). There are also properties related to the code point's use in
386bidirectional text and other display-related properties.
387
388The following program displays some information about several characters, and
389prints the numeric value of one particular character::
390
391 import unicodedata
Georg Brandl6911e3c2007-09-04 07:15:32 +0000392
Georg Brandlf6945182008-02-01 11:56:49 +0000393 u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000394
Georg Brandl116aa622007-08-15 14:28:22 +0000395 for i, c in enumerate(u):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000396 print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
397 print(unicodedata.name(c))
398
Georg Brandl116aa622007-08-15 14:28:22 +0000399 # Get numeric value of second character
Georg Brandl6911e3c2007-09-04 07:15:32 +0000400 print(unicodedata.numeric(u[1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402When run, this prints::
403
404 0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
405 1 0bf2 No TAMIL NUMBER ONE THOUSAND
406 2 0f84 Mn TIBETAN MARK HALANTA
407 3 1770 Lo TAGBANWA LETTER SA
408 4 33af So SQUARE RAD OVER S SQUARED
409 1000.0
410
411The category codes are abbreviations describing the nature of the character.
412These are grouped into categories such as "Letter", "Number", "Punctuation", or
413"Symbol", which in turn are broken up into subcategories. To take the codes
414from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means
415"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol,
416other". See
417<http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values> for a
418list of category codes.
419
420References
421----------
422
Georg Brandlf6945182008-02-01 11:56:49 +0000423The ``str`` type is described in the Python library reference at
424:ref:`typesseq`.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426The documentation for the :mod:`unicodedata` module.
427
428The documentation for the :mod:`codecs` module.
429
430Marc-André Lemburg gave a presentation at EuroPython 2002 titled "Python and
431Unicode". A PDF version of his slides is available at
432<http://www.egenix.com/files/python/Unicode-EPC2002-Talk.pdf>, and is an
433excellent overview of the design of Python's Unicode features.
434
435
436Reading and Writing Unicode Data
437================================
438
439Once you've written some code that works with Unicode data, the next problem is
440input/output. How do you get Unicode strings into your program, and how do you
441convert Unicode into a form suitable for storage or transmission?
442
443It's possible that you may not need to do anything depending on your input
444sources and output destinations; you should check whether the libraries used in
445your application support Unicode natively. XML parsers often return Unicode
446data, for example. Many relational databases also support Unicode-valued
447columns and can return Unicode values from an SQL query.
448
449Unicode data is usually converted to a particular encoding before it gets
450written to disk or sent over a socket. It's possible to do all the work
451yourself: open a file, read an 8-bit string from it, and convert the string with
452``unicode(str, encoding)``. However, the manual approach is not recommended.
453
454One problem is the multi-byte nature of encodings; one Unicode character can be
455represented by several bytes. If you want to read the file in arbitrary-sized
456chunks (say, 1K or 4K), you need to write error-handling code to catch the case
457where only part of the bytes encoding a single Unicode character are read at the
458end of a chunk. One solution would be to read the entire file into memory and
459then perform the decoding, but that prevents you from working with files that
460are extremely large; if you need to read a 2Gb file, you need 2Gb of RAM.
461(More, really, since for at least a moment you'd need to have both the encoded
462string and its Unicode version in memory.)
463
464The solution would be to use the low-level decoding interface to catch the case
465of partial coding sequences. The work of implementing this has already been
466done for you: the :mod:`codecs` module includes a version of the :func:`open`
467function that returns a file-like object that assumes the file's contents are in
468a specified encoding and accepts Unicode parameters for methods such as
469``.read()`` and ``.write()``.
470
471The function's parameters are ``open(filename, mode='rb', encoding=None,
472errors='strict', buffering=1)``. ``mode`` can be ``'r'``, ``'w'``, or ``'a'``,
473just like the corresponding parameter to the regular built-in ``open()``
474function; add a ``'+'`` to update the file. ``buffering`` is similarly parallel
475to the standard function's parameter. ``encoding`` is a string giving the
476encoding to use; if it's left as ``None``, a regular Python file object that
477accepts 8-bit strings is returned. Otherwise, a wrapper object is returned, and
478data written to or read from the wrapper object will be converted as needed.
479``errors`` specifies the action for encoding errors and can be one of the usual
480values of 'strict', 'ignore', and 'replace'.
481
482Reading Unicode from a file is therefore simple::
483
484 import codecs
485 f = codecs.open('unicode.rst', encoding='utf-8')
486 for line in f:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000487 print(repr(line))
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489It's also possible to open files in update mode, allowing both reading and
490writing::
491
492 f = codecs.open('test', encoding='utf-8', mode='w+')
Georg Brandlf6945182008-02-01 11:56:49 +0000493 f.write('\u4500 blah blah blah\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000494 f.seek(0)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000495 print(repr(f.readline()[:1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000496 f.close()
497
498Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
499written as the first character of a file in order to assist with autodetection
500of the file's byte ordering. Some encodings, such as UTF-16, expect a BOM to be
501present at the start of a file; when such an encoding is used, the BOM will be
502automatically written as the first character and will be silently dropped when
503the file is read. There are variants of these encodings, such as 'utf-16-le'
504and 'utf-16-be' for little-endian and big-endian encodings, that specify one
505particular byte ordering and don't skip the BOM.
506
507
508Unicode filenames
509-----------------
510
511Most of the operating systems in common use today support filenames that contain
512arbitrary Unicode characters. Usually this is implemented by converting the
513Unicode string into some encoding that varies depending on the system. For
514example, MacOS X uses UTF-8 while Windows uses a configurable encoding; on
515Windows, Python uses the name "mbcs" to refer to whatever the currently
516configured encoding is. On Unix systems, there will only be a filesystem
517encoding if you've set the ``LANG`` or ``LC_CTYPE`` environment variables; if
518you haven't, the default encoding is ASCII.
519
520The :func:`sys.getfilesystemencoding` function returns the encoding to use on
521your current system, in case you want to do the encoding manually, but there's
522not much reason to bother. When opening a file for reading or writing, you can
523usually just provide the Unicode string as the filename, and it will be
524automatically converted to the right encoding for you::
525
Georg Brandlf6945182008-02-01 11:56:49 +0000526 filename = 'filename\u4500abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000527 f = open(filename, 'w')
528 f.write('blah\n')
529 f.close()
530
531Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode
532filenames.
533
534:func:`os.listdir`, which returns filenames, raises an issue: should it return
535the Unicode version of filenames, or should it return 8-bit strings containing
536the encoded versions? :func:`os.listdir` will do both, depending on whether you
537provided the directory path as an 8-bit string or a Unicode string. If you pass
538a Unicode string as the path, filenames will be decoded using the filesystem's
539encoding and a list of Unicode strings will be returned, while passing an 8-bit
540path will return the 8-bit versions of the filenames. For example, assuming the
541default filesystem encoding is UTF-8, running the following program::
542
Georg Brandlf6945182008-02-01 11:56:49 +0000543 fn = 'filename\u4500abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000544 f = open(fn, 'w')
545 f.close()
546
547 import os
Georg Brandl6911e3c2007-09-04 07:15:32 +0000548 print(os.listdir('.'))
549 print(os.listdir(u'.'))
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551will produce the following output::
552
553 amk:~$ python t.py
554 ['.svn', 'filename\xe4\x94\x80abc', ...]
Georg Brandlf6945182008-02-01 11:56:49 +0000555 ['.svn', 'filename\u4500abc', ...]
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557The first list contains UTF-8-encoded filenames, and the second list contains
558the Unicode versions.
559
560
Georg Brandl6911e3c2007-09-04 07:15:32 +0000561
Georg Brandl116aa622007-08-15 14:28:22 +0000562Tips for Writing Unicode-aware Programs
563---------------------------------------
564
565This section provides some suggestions on writing software that deals with
566Unicode.
567
568The most important tip is:
569
570 Software should only work with Unicode strings internally, converting to a
571 particular encoding on output.
572
573If you attempt to write processing functions that accept both Unicode and 8-bit
574strings, you will find your program vulnerable to bugs wherever you combine the
575two different kinds of strings. Python's default encoding is ASCII, so whenever
576a character with an ASCII value > 127 is in the input data, you'll get a
577:exc:`UnicodeDecodeError` because that character can't be handled by the ASCII
578encoding.
579
580It's easy to miss such problems if you only test your software with data that
581doesn't contain any accents; everything will seem to work, but there's actually
582a bug in your program waiting for the first user who attempts to use characters
583> 127. A second tip, therefore, is:
584
585 Include characters > 127 and, even better, characters > 255 in your test
586 data.
587
588When using data coming from a web browser or some other untrusted source, a
589common technique is to check for illegal characters in a string before using the
590string in a generated command line or storing it in a database. If you're doing
591this, be careful to check the string once it's in the form that will be used or
592stored; it's possible for encodings to be used to disguise characters. This is
593especially true if the input data also specifies the encoding; many encodings
594leave the commonly checked-for characters alone, but Python includes some
595encodings such as ``'base64'`` that modify every single character.
596
597For example, let's say you have a content management system that takes a Unicode
598filename, and you want to disallow paths with a '/' character. You might write
599this code::
600
601 def read_file (filename, encoding):
602 if '/' in filename:
603 raise ValueError("'/' not allowed in filenames")
604 unicode_name = filename.decode(encoding)
605 f = open(unicode_name, 'r')
606 # ... return contents of file ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000607
Georg Brandl116aa622007-08-15 14:28:22 +0000608However, if an attacker could specify the ``'base64'`` encoding, they could pass
609``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
610``'/etc/passwd'``, to read a system file. The above code looks for ``'/'``
611characters in the encoded form and misses the dangerous character in the
612resulting decoded form.
613
614References
615----------
616
617The PDF slides for Marc-André Lemburg's presentation "Writing Unicode-aware
618Applications in Python" are available at
619<http://www.egenix.com/files/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf>
620and discuss questions of character encodings as well as how to internationalize
621and localize an application.
622
623
624Revision History and Acknowledgements
625=====================================
626
627Thanks to the following people who have noted errors or offered suggestions on
628this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
629Marc-André Lemburg, Martin von Löwis, Chad Whitacre.
630
631Version 1.0: posted August 5 2005.
632
633Version 1.01: posted August 7 2005. Corrects factual and markup errors; adds
634several links.
635
636Version 1.02: posted August 16 2005. Corrects factual errors.
637
638
639.. comment Additional topic: building Python w/ UCS2 or UCS4 support
640.. comment Describe obscure -U switch somewhere?
641.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
642
Georg Brandl6911e3c2007-09-04 07:15:32 +0000643.. comment
Georg Brandl116aa622007-08-15 14:28:22 +0000644 Original outline:
645
646 - [ ] Unicode introduction
647 - [ ] ASCII
648 - [ ] Terms
649 - [ ] Character
650 - [ ] Code point
651 - [ ] Encodings
652 - [ ] Common encodings: ASCII, Latin-1, UTF-8
653 - [ ] Unicode Python type
654 - [ ] Writing unicode literals
655 - [ ] Obscurity: -U switch
656 - [ ] Built-ins
657 - [ ] unichr()
658 - [ ] ord()
659 - [ ] unicode() constructor
660 - [ ] Unicode type
661 - [ ] encode(), decode() methods
662 - [ ] Unicodedata module for character properties
663 - [ ] I/O
664 - [ ] Reading/writing Unicode data into files
665 - [ ] Byte-order marks
666 - [ ] Unicode filenames
667 - [ ] Writing Unicode programs
668 - [ ] Do everything in Unicode
669 - [ ] Declaring source code encodings (PEP 263)
670 - [ ] Other issues
671 - [ ] Building Python (UCS2, UCS4)