blob: 454d25e7a249ad6226d1a4b2e00ce9311e653d26 [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
Georg Brandl116aa622007-08-15 14:28:22 +0000219Two other good introductory articles were written by Joel Spolsky
220<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff
221<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make
222things clear to you, you should try reading one of these alternate articles
223before continuing.
224
225Wikipedia entries are often helpful; see the entries for "character encoding"
226<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
227<http://en.wikipedia.org/wiki/UTF-8>, for example.
228
229
230Python's Unicode Support
231========================
232
233Now that you've learned the rudiments of Unicode, we can look at Python's
234Unicode features.
235
Georg Brandlf6945182008-02-01 11:56:49 +0000236The String Type
237---------------
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandlf6945182008-02-01 11:56:49 +0000239Since Python 3.0, the language features a ``str`` type that contain Unicode
240characters, meaning any string created using ``"unicode rocks!"``, ``'unicode
241rocks!``, or the triple-quoted string syntax is stored as Unicode.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandlf6945182008-02-01 11:56:49 +0000243To insert a Unicode character that is not part ASCII, e.g., any letters with
244accents, one can use escape sequences in their string literals as such::
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandlf6945182008-02-01 11:56:49 +0000246 >>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name
247 '\u0394'
248 >>> "\u0394" # Using a 16-bit hex value
249 '\u0394'
250 >>> "\U00000394" # Using a 32-bit hex value
251 '\u0394'
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandlf6945182008-02-01 11:56:49 +0000253In addition, one can create a string using the :func:`decode` method of
254:class:`bytes`. This method takes an encoding, such as UTF-8, and, optionally,
255an *errors* argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandlf6945182008-02-01 11:56:49 +0000257The *errors* argument specifies the response when the input string can't be
Georg Brandl116aa622007-08-15 14:28:22 +0000258converted according to the encoding's rules. Legal values for this argument are
Georg Brandlf6945182008-02-01 11:56:49 +0000259'strict' (raise a :exc:`UnicodeDecodeError` exception), 'replace' (add U+FFFD,
Georg Brandl116aa622007-08-15 14:28:22 +0000260'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the
261Unicode result). The following examples show the differences::
262
Georg Brandlf6945182008-02-01 11:56:49 +0000263 >>> b'\x80abc'.decode("utf-8", "strict")
Georg Brandl116aa622007-08-15 14:28:22 +0000264 Traceback (most recent call last):
265 File "<stdin>", line 1, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000266 UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
Georg Brandl116aa622007-08-15 14:28:22 +0000267 ordinal not in range(128)
Georg Brandlf6945182008-02-01 11:56:49 +0000268 >>> b'\x80abc'.decode("utf-8", "replace")
269 '\ufffdabc'
270 >>> b'\x80abc'.decode("utf-8", "ignore")
271 'abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Georg Brandlf6945182008-02-01 11:56:49 +0000273Encodings are specified as strings containing the encoding's name. Python
Georg Brandl116aa622007-08-15 14:28:22 +0000274comes with roughly 100 different encodings; see the Python Library Reference at
Christian Heimes2202f872008-02-06 14:31:34 +0000275:ref:`standard-encodings` for a list. Some encodings
Georg Brandl116aa622007-08-15 14:28:22 +0000276have multiple names; for example, 'latin-1', 'iso_8859_1' and '8859' are all
277synonyms for the same encoding.
278
Georg Brandlf6945182008-02-01 11:56:49 +0000279One-character Unicode strings can also be created with the :func:`chr`
Georg Brandl116aa622007-08-15 14:28:22 +0000280built-in function, which takes integers and returns a Unicode string of length 1
281that contains the corresponding code point. The reverse operation is the
282built-in :func:`ord` function that takes a one-character Unicode string and
283returns the code point value::
284
Georg Brandlf6945182008-02-01 11:56:49 +0000285 >>> chr(40960)
286 '\ua000'
287 >>> ord('\ua000')
Georg Brandl116aa622007-08-15 14:28:22 +0000288 40960
289
Georg Brandlf6945182008-02-01 11:56:49 +0000290Converting to Bytes
291-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Georg Brandlf6945182008-02-01 11:56:49 +0000293Another important str method is ``.encode([encoding], [errors='strict'])``,
294which returns a ``bytes`` representation of the Unicode string, encoded in the
295requested encoding. The ``errors`` parameter is the same as the parameter of
296the :meth:`decode` method, with one additional possibility; as well as 'strict',
Georg Brandl116aa622007-08-15 14:28:22 +0000297'ignore', and 'replace', you can also pass 'xmlcharrefreplace' which uses XML's
298character references. The following example shows the different results::
299
Georg Brandlf6945182008-02-01 11:56:49 +0000300 >>> u = chr(40960) + 'abcd' + chr(1972)
Georg Brandl116aa622007-08-15 14:28:22 +0000301 >>> u.encode('utf-8')
Georg Brandlf6945182008-02-01 11:56:49 +0000302 b'\xea\x80\x80abcd\xde\xb4'
Georg Brandl116aa622007-08-15 14:28:22 +0000303 >>> u.encode('ascii')
304 Traceback (most recent call last):
305 File "<stdin>", line 1, in ?
306 UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
307 >>> u.encode('ascii', 'ignore')
Georg Brandlf6945182008-02-01 11:56:49 +0000308 b'abcd'
Georg Brandl116aa622007-08-15 14:28:22 +0000309 >>> u.encode('ascii', 'replace')
Georg Brandlf6945182008-02-01 11:56:49 +0000310 b'?abcd?'
Georg Brandl116aa622007-08-15 14:28:22 +0000311 >>> u.encode('ascii', 'xmlcharrefreplace')
Georg Brandlf6945182008-02-01 11:56:49 +0000312 b'&#40960;abcd&#1972;'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000313
Georg Brandl116aa622007-08-15 14:28:22 +0000314The low-level routines for registering and accessing the available encodings are
315found in the :mod:`codecs` module. However, the encoding and decoding functions
316returned by this module are usually more low-level than is comfortable, so I'm
317not going to describe the :mod:`codecs` module here. If you need to implement a
318completely new encoding, you'll need to learn about the :mod:`codecs` module
319interfaces, but implementing encodings is a specialized task that also won't be
320covered here. Consult the Python documentation to learn more about this module.
321
322The most commonly used part of the :mod:`codecs` module is the
323:func:`codecs.open` function which will be discussed in the section on input and
324output.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000325
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327Unicode Literals in Python Source Code
328--------------------------------------
329
Georg Brandlf6945182008-02-01 11:56:49 +0000330In Python source code, specific Unicode code points can be written using the
331``\u`` escape sequence, which is followed by four hex digits giving the code
332point. The ``\U`` escape sequence is similar, but expects 8 hex digits, not 4::
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Georg Brandlf6945182008-02-01 11:56:49 +0000334 >>> s = "a\xac\u1234\u20ac\U00008000"
335 ^^^^ two-digit hex escape
336 ^^^^^ four-digit Unicode escape
337 ^^^^^^^^^^ eight-digit Unicode escape
Georg Brandl6911e3c2007-09-04 07:15:32 +0000338 >>> for c in s: print(ord(c), end=" ")
339 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000340 97 172 4660 8364 32768
341
342Using escape sequences for code points greater than 127 is fine in small doses,
343but becomes an annoyance if you're using many accented characters, as you would
344in a program with messages in French or some other accent-using language. You
Georg Brandlf6945182008-02-01 11:56:49 +0000345can also assemble strings using the :func:`chr` built-in function, but this is
Georg Brandl116aa622007-08-15 14:28:22 +0000346even more tedious.
347
348Ideally, you'd want to be able to write literals in your language's natural
349encoding. You could then edit Python source code with your favorite editor
350which would display the accented characters naturally, and have the right
351characters used at runtime.
352
Georg Brandlf6945182008-02-01 11:56:49 +0000353Python supports writing Unicode literals in UTF-8 by default, but you can use
354(almost) any encoding if you declare the encoding being used. This is done by
355including a special comment as either the first or second line of the source
356file::
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 #!/usr/bin/env python
359 # -*- coding: latin-1 -*-
Georg Brandl6911e3c2007-09-04 07:15:32 +0000360
Georg Brandlf6945182008-02-01 11:56:49 +0000361 u = 'abcdé'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000362 print(ord(u[-1]))
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364The syntax is inspired by Emacs's notation for specifying variables local to a
365file. Emacs supports many different variables, but Python only supports
366'coding'. The ``-*-`` symbols indicate that the comment is special; within
367them, you must supply the name ``coding`` and the name of your chosen encoding,
368separated by ``':'``.
369
Georg Brandlf6945182008-02-01 11:56:49 +0000370If you don't include such a comment, the default encoding used will be UTF-8 as
371already mentioned.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000372
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374Unicode Properties
375------------------
376
377The Unicode specification includes a database of information about code points.
378For each code point that's defined, the information includes the character's
379name, its category, the numeric value if applicable (Unicode has characters
380representing the Roman numerals and fractions such as one-third and
381four-fifths). There are also properties related to the code point's use in
382bidirectional text and other display-related properties.
383
384The following program displays some information about several characters, and
385prints the numeric value of one particular character::
386
387 import unicodedata
Georg Brandl6911e3c2007-09-04 07:15:32 +0000388
Georg Brandlf6945182008-02-01 11:56:49 +0000389 u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000390
Georg Brandl116aa622007-08-15 14:28:22 +0000391 for i, c in enumerate(u):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000392 print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
393 print(unicodedata.name(c))
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395 # Get numeric value of second character
Georg Brandl6911e3c2007-09-04 07:15:32 +0000396 print(unicodedata.numeric(u[1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398When run, this prints::
399
400 0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
401 1 0bf2 No TAMIL NUMBER ONE THOUSAND
402 2 0f84 Mn TIBETAN MARK HALANTA
403 3 1770 Lo TAGBANWA LETTER SA
404 4 33af So SQUARE RAD OVER S SQUARED
405 1000.0
406
407The category codes are abbreviations describing the nature of the character.
408These are grouped into categories such as "Letter", "Number", "Punctuation", or
409"Symbol", which in turn are broken up into subcategories. To take the codes
410from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means
411"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol,
412other". See
413<http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values> for a
414list of category codes.
415
416References
417----------
418
Georg Brandlf6945182008-02-01 11:56:49 +0000419The ``str`` type is described in the Python library reference at
420:ref:`typesseq`.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422The documentation for the :mod:`unicodedata` module.
423
424The documentation for the :mod:`codecs` module.
425
426Marc-André Lemburg gave a presentation at EuroPython 2002 titled "Python and
427Unicode". A PDF version of his slides is available at
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000428<http://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf>, and is an
Georg Brandl116aa622007-08-15 14:28:22 +0000429excellent overview of the design of Python's Unicode features.
430
431
432Reading and Writing Unicode Data
433================================
434
435Once you've written some code that works with Unicode data, the next problem is
436input/output. How do you get Unicode strings into your program, and how do you
437convert Unicode into a form suitable for storage or transmission?
438
439It's possible that you may not need to do anything depending on your input
440sources and output destinations; you should check whether the libraries used in
441your application support Unicode natively. XML parsers often return Unicode
442data, for example. Many relational databases also support Unicode-valued
443columns and can return Unicode values from an SQL query.
444
445Unicode data is usually converted to a particular encoding before it gets
446written to disk or sent over a socket. It's possible to do all the work
447yourself: open a file, read an 8-bit string from it, and convert the string with
448``unicode(str, encoding)``. However, the manual approach is not recommended.
449
450One problem is the multi-byte nature of encodings; one Unicode character can be
451represented by several bytes. If you want to read the file in arbitrary-sized
452chunks (say, 1K or 4K), you need to write error-handling code to catch the case
453where only part of the bytes encoding a single Unicode character are read at the
454end of a chunk. One solution would be to read the entire file into memory and
455then perform the decoding, but that prevents you from working with files that
456are extremely large; if you need to read a 2Gb file, you need 2Gb of RAM.
457(More, really, since for at least a moment you'd need to have both the encoded
458string and its Unicode version in memory.)
459
460The solution would be to use the low-level decoding interface to catch the case
461of partial coding sequences. The work of implementing this has already been
462done for you: the :mod:`codecs` module includes a version of the :func:`open`
463function that returns a file-like object that assumes the file's contents are in
464a specified encoding and accepts Unicode parameters for methods such as
465``.read()`` and ``.write()``.
466
467The function's parameters are ``open(filename, mode='rb', encoding=None,
468errors='strict', buffering=1)``. ``mode`` can be ``'r'``, ``'w'``, or ``'a'``,
469just like the corresponding parameter to the regular built-in ``open()``
470function; add a ``'+'`` to update the file. ``buffering`` is similarly parallel
471to the standard function's parameter. ``encoding`` is a string giving the
472encoding to use; if it's left as ``None``, a regular Python file object that
473accepts 8-bit strings is returned. Otherwise, a wrapper object is returned, and
474data written to or read from the wrapper object will be converted as needed.
475``errors`` specifies the action for encoding errors and can be one of the usual
476values of 'strict', 'ignore', and 'replace'.
477
478Reading Unicode from a file is therefore simple::
479
480 import codecs
481 f = codecs.open('unicode.rst', encoding='utf-8')
482 for line in f:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000483 print(repr(line))
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485It's also possible to open files in update mode, allowing both reading and
486writing::
487
488 f = codecs.open('test', encoding='utf-8', mode='w+')
Georg Brandlf6945182008-02-01 11:56:49 +0000489 f.write('\u4500 blah blah blah\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000490 f.seek(0)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000491 print(repr(f.readline()[:1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000492 f.close()
493
494Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
495written as the first character of a file in order to assist with autodetection
496of the file's byte ordering. Some encodings, such as UTF-16, expect a BOM to be
497present at the start of a file; when such an encoding is used, the BOM will be
498automatically written as the first character and will be silently dropped when
499the file is read. There are variants of these encodings, such as 'utf-16-le'
500and 'utf-16-be' for little-endian and big-endian encodings, that specify one
501particular byte ordering and don't skip the BOM.
502
503
504Unicode filenames
505-----------------
506
507Most of the operating systems in common use today support filenames that contain
508arbitrary Unicode characters. Usually this is implemented by converting the
509Unicode string into some encoding that varies depending on the system. For
510example, MacOS X uses UTF-8 while Windows uses a configurable encoding; on
511Windows, Python uses the name "mbcs" to refer to whatever the currently
512configured encoding is. On Unix systems, there will only be a filesystem
513encoding if you've set the ``LANG`` or ``LC_CTYPE`` environment variables; if
514you haven't, the default encoding is ASCII.
515
516The :func:`sys.getfilesystemencoding` function returns the encoding to use on
517your current system, in case you want to do the encoding manually, but there's
518not much reason to bother. When opening a file for reading or writing, you can
519usually just provide the Unicode string as the filename, and it will be
520automatically converted to the right encoding for you::
521
Georg Brandlf6945182008-02-01 11:56:49 +0000522 filename = 'filename\u4500abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000523 f = open(filename, 'w')
524 f.write('blah\n')
525 f.close()
526
527Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode
528filenames.
529
530:func:`os.listdir`, which returns filenames, raises an issue: should it return
531the Unicode version of filenames, or should it return 8-bit strings containing
532the encoded versions? :func:`os.listdir` will do both, depending on whether you
533provided the directory path as an 8-bit string or a Unicode string. If you pass
534a Unicode string as the path, filenames will be decoded using the filesystem's
535encoding and a list of Unicode strings will be returned, while passing an 8-bit
536path will return the 8-bit versions of the filenames. For example, assuming the
537default filesystem encoding is UTF-8, running the following program::
538
Georg Brandlf6945182008-02-01 11:56:49 +0000539 fn = 'filename\u4500abc'
Georg Brandl116aa622007-08-15 14:28:22 +0000540 f = open(fn, 'w')
541 f.close()
542
543 import os
Georg Brandl6911e3c2007-09-04 07:15:32 +0000544 print(os.listdir('.'))
545 print(os.listdir(u'.'))
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547will produce the following output::
548
549 amk:~$ python t.py
550 ['.svn', 'filename\xe4\x94\x80abc', ...]
Georg Brandlf6945182008-02-01 11:56:49 +0000551 ['.svn', 'filename\u4500abc', ...]
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553The first list contains UTF-8-encoded filenames, and the second list contains
554the Unicode versions.
555
556
Georg Brandl6911e3c2007-09-04 07:15:32 +0000557
Georg Brandl116aa622007-08-15 14:28:22 +0000558Tips for Writing Unicode-aware Programs
559---------------------------------------
560
561This section provides some suggestions on writing software that deals with
562Unicode.
563
564The most important tip is:
565
566 Software should only work with Unicode strings internally, converting to a
567 particular encoding on output.
568
569If you attempt to write processing functions that accept both Unicode and 8-bit
570strings, you will find your program vulnerable to bugs wherever you combine the
571two different kinds of strings. Python's default encoding is ASCII, so whenever
572a character with an ASCII value > 127 is in the input data, you'll get a
573:exc:`UnicodeDecodeError` because that character can't be handled by the ASCII
574encoding.
575
576It's easy to miss such problems if you only test your software with data that
577doesn't contain any accents; everything will seem to work, but there's actually
578a bug in your program waiting for the first user who attempts to use characters
579> 127. A second tip, therefore, is:
580
581 Include characters > 127 and, even better, characters > 255 in your test
582 data.
583
584When using data coming from a web browser or some other untrusted source, a
585common technique is to check for illegal characters in a string before using the
586string in a generated command line or storing it in a database. If you're doing
587this, be careful to check the string once it's in the form that will be used or
588stored; it's possible for encodings to be used to disguise characters. This is
589especially true if the input data also specifies the encoding; many encodings
590leave the commonly checked-for characters alone, but Python includes some
591encodings such as ``'base64'`` that modify every single character.
592
593For example, let's say you have a content management system that takes a Unicode
594filename, and you want to disallow paths with a '/' character. You might write
595this code::
596
597 def read_file (filename, encoding):
598 if '/' in filename:
599 raise ValueError("'/' not allowed in filenames")
600 unicode_name = filename.decode(encoding)
601 f = open(unicode_name, 'r')
602 # ... return contents of file ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000603
Georg Brandl116aa622007-08-15 14:28:22 +0000604However, if an attacker could specify the ``'base64'`` encoding, they could pass
605``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
606``'/etc/passwd'``, to read a system file. The above code looks for ``'/'``
607characters in the encoded form and misses the dangerous character in the
608resulting decoded form.
609
610References
611----------
612
613The PDF slides for Marc-André Lemburg's presentation "Writing Unicode-aware
614Applications in Python" are available at
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000615<http://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf>
Georg Brandl116aa622007-08-15 14:28:22 +0000616and discuss questions of character encodings as well as how to internationalize
617and localize an application.
618
619
620Revision History and Acknowledgements
621=====================================
622
623Thanks to the following people who have noted errors or offered suggestions on
624this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
625Marc-André Lemburg, Martin von Löwis, Chad Whitacre.
626
627Version 1.0: posted August 5 2005.
628
629Version 1.01: posted August 7 2005. Corrects factual and markup errors; adds
630several links.
631
632Version 1.02: posted August 16 2005. Corrects factual errors.
633
634
635.. comment Additional topic: building Python w/ UCS2 or UCS4 support
636.. comment Describe obscure -U switch somewhere?
637.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
638
Georg Brandl6911e3c2007-09-04 07:15:32 +0000639.. comment
Georg Brandl116aa622007-08-15 14:28:22 +0000640 Original outline:
641
642 - [ ] Unicode introduction
643 - [ ] ASCII
644 - [ ] Terms
645 - [ ] Character
646 - [ ] Code point
647 - [ ] Encodings
648 - [ ] Common encodings: ASCII, Latin-1, UTF-8
649 - [ ] Unicode Python type
650 - [ ] Writing unicode literals
651 - [ ] Obscurity: -U switch
652 - [ ] Built-ins
653 - [ ] unichr()
654 - [ ] ord()
655 - [ ] unicode() constructor
656 - [ ] Unicode type
657 - [ ] encode(), decode() methods
658 - [ ] Unicodedata module for character properties
659 - [ ] I/O
660 - [ ] Reading/writing Unicode data into files
661 - [ ] Byte-order marks
662 - [ ] Unicode filenames
663 - [ ] Writing Unicode programs
664 - [ ] Do everything in Unicode
665 - [ ] Declaring source code encodings (PEP 263)
666 - [ ] Other issues
667 - [ ] Building Python (UCS2, UCS4)