blob: 8b520393ed8261e1afcca9e4bacb375560708a8e [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
240
241The Unicode Type
242----------------
243
244Unicode strings are expressed as instances of the :class:`unicode` type, one of
245Python's repertoire of built-in types. It derives from an abstract type called
246:class:`basestring`, which is also an ancestor of the :class:`str` type; you can
247therefore check if a value is a string type with ``isinstance(value,
248basestring)``. Under the hood, Python represents Unicode strings as either 16-
249or 32-bit integers, depending on how the Python interpreter was compiled.
250
251The :func:`unicode` constructor has the signature ``unicode(string[, encoding,
252errors])``. All of its arguments should be 8-bit strings. The first argument
253is converted to Unicode using the specified encoding; if you leave off the
254``encoding`` argument, the ASCII encoding is used for the conversion, so
255characters greater than 127 will be treated as errors::
256
257 >>> unicode('abcdef')
258 u'abcdef'
259 >>> s = unicode('abcdef')
260 >>> type(s)
261 <type 'unicode'>
262 >>> unicode('abcdef' + chr(255))
263 Traceback (most recent call last):
264 File "<stdin>", line 1, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000265 UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
Georg Brandl116aa622007-08-15 14:28:22 +0000266 ordinal not in range(128)
267
268The ``errors`` argument specifies the response when the input string can't be
269converted according to the encoding's rules. Legal values for this argument are
270'strict' (raise a ``UnicodeDecodeError`` exception), 'replace' (add U+FFFD,
271'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the
272Unicode result). The following examples show the differences::
273
274 >>> unicode('\x80abc', errors='strict')
275 Traceback (most recent call last):
276 File "<stdin>", line 1, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000277 UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
Georg Brandl116aa622007-08-15 14:28:22 +0000278 ordinal not in range(128)
279 >>> unicode('\x80abc', errors='replace')
280 u'\ufffdabc'
281 >>> unicode('\x80abc', errors='ignore')
282 u'abc'
283
284Encodings are specified as strings containing the encoding's name. Python 2.4
285comes with roughly 100 different encodings; see the Python Library Reference at
286<http://docs.python.org/lib/standard-encodings.html> for a list. Some encodings
287have multiple names; for example, 'latin-1', 'iso_8859_1' and '8859' are all
288synonyms for the same encoding.
289
290One-character Unicode strings can also be created with the :func:`unichr`
291built-in function, which takes integers and returns a Unicode string of length 1
292that contains the corresponding code point. The reverse operation is the
293built-in :func:`ord` function that takes a one-character Unicode string and
294returns the code point value::
295
296 >>> unichr(40960)
297 u'\ua000'
298 >>> ord(u'\ua000')
299 40960
300
301Instances of the :class:`unicode` type have many of the same methods as the
3028-bit string type for operations such as searching and formatting::
303
304 >>> s = u'Was ever feather so lightly blown to and fro as this multitude?'
305 >>> s.count('e')
306 5
307 >>> s.find('feather')
308 9
309 >>> s.find('bird')
310 -1
311 >>> s.replace('feather', 'sand')
312 u'Was ever sand so lightly blown to and fro as this multitude?'
313 >>> s.upper()
314 u'WAS EVER FEATHER SO LIGHTLY BLOWN TO AND FRO AS THIS MULTITUDE?'
315
316Note that the arguments to these methods can be Unicode strings or 8-bit
317strings. 8-bit strings will be converted to Unicode before carrying out the
318operation; Python's default ASCII encoding will be used, so characters greater
319than 127 will cause an exception::
320
321 >>> s.find('Was\x9f')
322 Traceback (most recent call last):
323 File "<stdin>", line 1, in ?
324 UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3: ordinal not in range(128)
325 >>> s.find(u'Was\x9f')
326 -1
327
328Much Python code that operates on strings will therefore work with Unicode
329strings without requiring any changes to the code. (Input and output code needs
330more updating for Unicode; more on this later.)
331
332Another important method is ``.encode([encoding], [errors='strict'])``, which
333returns an 8-bit string version of the Unicode string, encoded in the requested
334encoding. The ``errors`` parameter is the same as the parameter of the
335``unicode()`` constructor, with one additional possibility; as well as 'strict',
336'ignore', and 'replace', you can also pass 'xmlcharrefreplace' which uses XML's
337character references. The following example shows the different results::
338
339 >>> u = unichr(40960) + u'abcd' + unichr(1972)
340 >>> u.encode('utf-8')
341 '\xea\x80\x80abcd\xde\xb4'
342 >>> u.encode('ascii')
343 Traceback (most recent call last):
344 File "<stdin>", line 1, in ?
345 UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
346 >>> u.encode('ascii', 'ignore')
347 'abcd'
348 >>> u.encode('ascii', 'replace')
349 '?abcd?'
350 >>> u.encode('ascii', 'xmlcharrefreplace')
351 '&#40960;abcd&#1972;'
352
353Python's 8-bit strings have a ``.decode([encoding], [errors])`` method that
354interprets the string using the given encoding::
355
356 >>> u = unichr(40960) + u'abcd' + unichr(1972) # Assemble a string
357 >>> utf8_version = u.encode('utf-8') # Encode as UTF-8
358 >>> type(utf8_version), utf8_version
359 (<type 'str'>, '\xea\x80\x80abcd\xde\xb4')
360 >>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8
361 >>> u == u2 # The two strings match
362 True
Georg Brandl6911e3c2007-09-04 07:15:32 +0000363
Georg Brandl116aa622007-08-15 14:28:22 +0000364The low-level routines for registering and accessing the available encodings are
365found in the :mod:`codecs` module. However, the encoding and decoding functions
366returned by this module are usually more low-level than is comfortable, so I'm
367not going to describe the :mod:`codecs` module here. If you need to implement a
368completely new encoding, you'll need to learn about the :mod:`codecs` module
369interfaces, but implementing encodings is a specialized task that also won't be
370covered here. Consult the Python documentation to learn more about this module.
371
372The most commonly used part of the :mod:`codecs` module is the
373:func:`codecs.open` function which will be discussed in the section on input and
374output.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000375
376
Georg Brandl116aa622007-08-15 14:28:22 +0000377Unicode Literals in Python Source Code
378--------------------------------------
379
380In Python source code, Unicode literals are written as strings prefixed with the
381'u' or 'U' character: ``u'abcdefghijk'``. Specific code points can be written
382using the ``\u`` escape sequence, which is followed by four hex digits giving
383the code point. The ``\U`` escape sequence is similar, but expects 8 hex
384digits, not 4.
385
386Unicode literals can also use the same escape sequences as 8-bit strings,
387including ``\x``, but ``\x`` only takes two hex digits so it can't express an
388arbitrary code point. Octal escapes can go up to U+01ff, which is octal 777.
389
390::
391
392 >>> s = u"a\xac\u1234\u20ac\U00008000"
393 ^^^^ two-digit hex escape
Georg Brandl6911e3c2007-09-04 07:15:32 +0000394 ^^^^^^ four-digit Unicode escape
Georg Brandl116aa622007-08-15 14:28:22 +0000395 ^^^^^^^^^^ eight-digit Unicode escape
Georg Brandl6911e3c2007-09-04 07:15:32 +0000396 >>> for c in s: print(ord(c), end=" ")
397 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000398 97 172 4660 8364 32768
399
400Using escape sequences for code points greater than 127 is fine in small doses,
401but becomes an annoyance if you're using many accented characters, as you would
402in a program with messages in French or some other accent-using language. You
403can also assemble strings using the :func:`unichr` built-in function, but this is
404even more tedious.
405
406Ideally, you'd want to be able to write literals in your language's natural
407encoding. You could then edit Python source code with your favorite editor
408which would display the accented characters naturally, and have the right
409characters used at runtime.
410
411Python supports writing Unicode literals in any encoding, but you have to
412declare the encoding being used. This is done by including a special comment as
413either the first or second line of the source file::
414
415 #!/usr/bin/env python
416 # -*- coding: latin-1 -*-
Georg Brandl6911e3c2007-09-04 07:15:32 +0000417
Georg Brandl116aa622007-08-15 14:28:22 +0000418 u = u'abcdé'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000419 print(ord(u[-1]))
420
Georg Brandl116aa622007-08-15 14:28:22 +0000421The syntax is inspired by Emacs's notation for specifying variables local to a
422file. Emacs supports many different variables, but Python only supports
423'coding'. The ``-*-`` symbols indicate that the comment is special; within
424them, you must supply the name ``coding`` and the name of your chosen encoding,
425separated by ``':'``.
426
427If you don't include such a comment, the default encoding used will be ASCII.
428Versions of Python before 2.4 were Euro-centric and assumed Latin-1 as a default
429encoding for string literals; in Python 2.4, characters greater than 127 still
430work but result in a warning. For example, the following program has no
431encoding declaration::
432
433 #!/usr/bin/env python
434 u = u'abcdé'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000435 print(ord(u[-1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437When you run it with Python 2.4, it will output the following warning::
438
439 amk:~$ python p263.py
Georg Brandl6911e3c2007-09-04 07:15:32 +0000440 sys:1: DeprecationWarning: Non-ASCII character '\xe9'
441 in file p263.py on line 2, but no encoding declared;
Georg Brandl116aa622007-08-15 14:28:22 +0000442 see http://www.python.org/peps/pep-0263.html for details
Georg Brandl6911e3c2007-09-04 07:15:32 +0000443
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445Unicode Properties
446------------------
447
448The Unicode specification includes a database of information about code points.
449For each code point that's defined, the information includes the character's
450name, its category, the numeric value if applicable (Unicode has characters
451representing the Roman numerals and fractions such as one-third and
452four-fifths). There are also properties related to the code point's use in
453bidirectional text and other display-related properties.
454
455The following program displays some information about several characters, and
456prints the numeric value of one particular character::
457
458 import unicodedata
Georg Brandl6911e3c2007-09-04 07:15:32 +0000459
Georg Brandl116aa622007-08-15 14:28:22 +0000460 u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000461
Georg Brandl116aa622007-08-15 14:28:22 +0000462 for i, c in enumerate(u):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000463 print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
464 print(unicodedata.name(c))
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466 # Get numeric value of second character
Georg Brandl6911e3c2007-09-04 07:15:32 +0000467 print(unicodedata.numeric(u[1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469When run, this prints::
470
471 0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
472 1 0bf2 No TAMIL NUMBER ONE THOUSAND
473 2 0f84 Mn TIBETAN MARK HALANTA
474 3 1770 Lo TAGBANWA LETTER SA
475 4 33af So SQUARE RAD OVER S SQUARED
476 1000.0
477
478The category codes are abbreviations describing the nature of the character.
479These are grouped into categories such as "Letter", "Number", "Punctuation", or
480"Symbol", which in turn are broken up into subcategories. To take the codes
481from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means
482"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol,
483other". See
484<http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values> for a
485list of category codes.
486
487References
488----------
489
490The Unicode and 8-bit string types are described in the Python library reference
491at :ref:`typesseq`.
492
493The documentation for the :mod:`unicodedata` module.
494
495The documentation for the :mod:`codecs` module.
496
497Marc-André Lemburg gave a presentation at EuroPython 2002 titled "Python and
498Unicode". A PDF version of his slides is available at
499<http://www.egenix.com/files/python/Unicode-EPC2002-Talk.pdf>, and is an
500excellent overview of the design of Python's Unicode features.
501
502
503Reading and Writing Unicode Data
504================================
505
506Once you've written some code that works with Unicode data, the next problem is
507input/output. How do you get Unicode strings into your program, and how do you
508convert Unicode into a form suitable for storage or transmission?
509
510It's possible that you may not need to do anything depending on your input
511sources and output destinations; you should check whether the libraries used in
512your application support Unicode natively. XML parsers often return Unicode
513data, for example. Many relational databases also support Unicode-valued
514columns and can return Unicode values from an SQL query.
515
516Unicode data is usually converted to a particular encoding before it gets
517written to disk or sent over a socket. It's possible to do all the work
518yourself: open a file, read an 8-bit string from it, and convert the string with
519``unicode(str, encoding)``. However, the manual approach is not recommended.
520
521One problem is the multi-byte nature of encodings; one Unicode character can be
522represented by several bytes. If you want to read the file in arbitrary-sized
523chunks (say, 1K or 4K), you need to write error-handling code to catch the case
524where only part of the bytes encoding a single Unicode character are read at the
525end of a chunk. One solution would be to read the entire file into memory and
526then perform the decoding, but that prevents you from working with files that
527are extremely large; if you need to read a 2Gb file, you need 2Gb of RAM.
528(More, really, since for at least a moment you'd need to have both the encoded
529string and its Unicode version in memory.)
530
531The solution would be to use the low-level decoding interface to catch the case
532of partial coding sequences. The work of implementing this has already been
533done for you: the :mod:`codecs` module includes a version of the :func:`open`
534function that returns a file-like object that assumes the file's contents are in
535a specified encoding and accepts Unicode parameters for methods such as
536``.read()`` and ``.write()``.
537
538The function's parameters are ``open(filename, mode='rb', encoding=None,
539errors='strict', buffering=1)``. ``mode`` can be ``'r'``, ``'w'``, or ``'a'``,
540just like the corresponding parameter to the regular built-in ``open()``
541function; add a ``'+'`` to update the file. ``buffering`` is similarly parallel
542to the standard function's parameter. ``encoding`` is a string giving the
543encoding to use; if it's left as ``None``, a regular Python file object that
544accepts 8-bit strings is returned. Otherwise, a wrapper object is returned, and
545data written to or read from the wrapper object will be converted as needed.
546``errors`` specifies the action for encoding errors and can be one of the usual
547values of 'strict', 'ignore', and 'replace'.
548
549Reading Unicode from a file is therefore simple::
550
551 import codecs
552 f = codecs.open('unicode.rst', encoding='utf-8')
553 for line in f:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000554 print(repr(line))
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556It's also possible to open files in update mode, allowing both reading and
557writing::
558
559 f = codecs.open('test', encoding='utf-8', mode='w+')
560 f.write(u'\u4500 blah blah blah\n')
561 f.seek(0)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000562 print(repr(f.readline()[:1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000563 f.close()
564
565Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
566written as the first character of a file in order to assist with autodetection
567of the file's byte ordering. Some encodings, such as UTF-16, expect a BOM to be
568present at the start of a file; when such an encoding is used, the BOM will be
569automatically written as the first character and will be silently dropped when
570the file is read. There are variants of these encodings, such as 'utf-16-le'
571and 'utf-16-be' for little-endian and big-endian encodings, that specify one
572particular byte ordering and don't skip the BOM.
573
574
575Unicode filenames
576-----------------
577
578Most of the operating systems in common use today support filenames that contain
579arbitrary Unicode characters. Usually this is implemented by converting the
580Unicode string into some encoding that varies depending on the system. For
581example, MacOS X uses UTF-8 while Windows uses a configurable encoding; on
582Windows, Python uses the name "mbcs" to refer to whatever the currently
583configured encoding is. On Unix systems, there will only be a filesystem
584encoding if you've set the ``LANG`` or ``LC_CTYPE`` environment variables; if
585you haven't, the default encoding is ASCII.
586
587The :func:`sys.getfilesystemencoding` function returns the encoding to use on
588your current system, in case you want to do the encoding manually, but there's
589not much reason to bother. When opening a file for reading or writing, you can
590usually just provide the Unicode string as the filename, and it will be
591automatically converted to the right encoding for you::
592
593 filename = u'filename\u4500abc'
594 f = open(filename, 'w')
595 f.write('blah\n')
596 f.close()
597
598Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode
599filenames.
600
601:func:`os.listdir`, which returns filenames, raises an issue: should it return
602the Unicode version of filenames, or should it return 8-bit strings containing
603the encoded versions? :func:`os.listdir` will do both, depending on whether you
604provided the directory path as an 8-bit string or a Unicode string. If you pass
605a Unicode string as the path, filenames will be decoded using the filesystem's
606encoding and a list of Unicode strings will be returned, while passing an 8-bit
607path will return the 8-bit versions of the filenames. For example, assuming the
608default filesystem encoding is UTF-8, running the following program::
609
610 fn = u'filename\u4500abc'
611 f = open(fn, 'w')
612 f.close()
613
614 import os
Georg Brandl6911e3c2007-09-04 07:15:32 +0000615 print(os.listdir('.'))
616 print(os.listdir(u'.'))
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618will produce the following output::
619
620 amk:~$ python t.py
621 ['.svn', 'filename\xe4\x94\x80abc', ...]
622 [u'.svn', u'filename\u4500abc', ...]
623
624The first list contains UTF-8-encoded filenames, and the second list contains
625the Unicode versions.
626
627
Georg Brandl6911e3c2007-09-04 07:15:32 +0000628
Georg Brandl116aa622007-08-15 14:28:22 +0000629Tips for Writing Unicode-aware Programs
630---------------------------------------
631
632This section provides some suggestions on writing software that deals with
633Unicode.
634
635The most important tip is:
636
637 Software should only work with Unicode strings internally, converting to a
638 particular encoding on output.
639
640If you attempt to write processing functions that accept both Unicode and 8-bit
641strings, you will find your program vulnerable to bugs wherever you combine the
642two different kinds of strings. Python's default encoding is ASCII, so whenever
643a character with an ASCII value > 127 is in the input data, you'll get a
644:exc:`UnicodeDecodeError` because that character can't be handled by the ASCII
645encoding.
646
647It's easy to miss such problems if you only test your software with data that
648doesn't contain any accents; everything will seem to work, but there's actually
649a bug in your program waiting for the first user who attempts to use characters
650> 127. A second tip, therefore, is:
651
652 Include characters > 127 and, even better, characters > 255 in your test
653 data.
654
655When using data coming from a web browser or some other untrusted source, a
656common technique is to check for illegal characters in a string before using the
657string in a generated command line or storing it in a database. If you're doing
658this, be careful to check the string once it's in the form that will be used or
659stored; it's possible for encodings to be used to disguise characters. This is
660especially true if the input data also specifies the encoding; many encodings
661leave the commonly checked-for characters alone, but Python includes some
662encodings such as ``'base64'`` that modify every single character.
663
664For example, let's say you have a content management system that takes a Unicode
665filename, and you want to disallow paths with a '/' character. You might write
666this code::
667
668 def read_file (filename, encoding):
669 if '/' in filename:
670 raise ValueError("'/' not allowed in filenames")
671 unicode_name = filename.decode(encoding)
672 f = open(unicode_name, 'r')
673 # ... return contents of file ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000674
Georg Brandl116aa622007-08-15 14:28:22 +0000675However, if an attacker could specify the ``'base64'`` encoding, they could pass
676``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
677``'/etc/passwd'``, to read a system file. The above code looks for ``'/'``
678characters in the encoded form and misses the dangerous character in the
679resulting decoded form.
680
681References
682----------
683
684The PDF slides for Marc-André Lemburg's presentation "Writing Unicode-aware
685Applications in Python" are available at
686<http://www.egenix.com/files/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf>
687and discuss questions of character encodings as well as how to internationalize
688and localize an application.
689
690
691Revision History and Acknowledgements
692=====================================
693
694Thanks to the following people who have noted errors or offered suggestions on
695this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
696Marc-André Lemburg, Martin von Löwis, Chad Whitacre.
697
698Version 1.0: posted August 5 2005.
699
700Version 1.01: posted August 7 2005. Corrects factual and markup errors; adds
701several links.
702
703Version 1.02: posted August 16 2005. Corrects factual errors.
704
705
706.. comment Additional topic: building Python w/ UCS2 or UCS4 support
707.. comment Describe obscure -U switch somewhere?
708.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
709
Georg Brandl6911e3c2007-09-04 07:15:32 +0000710.. comment
Georg Brandl116aa622007-08-15 14:28:22 +0000711 Original outline:
712
713 - [ ] Unicode introduction
714 - [ ] ASCII
715 - [ ] Terms
716 - [ ] Character
717 - [ ] Code point
718 - [ ] Encodings
719 - [ ] Common encodings: ASCII, Latin-1, UTF-8
720 - [ ] Unicode Python type
721 - [ ] Writing unicode literals
722 - [ ] Obscurity: -U switch
723 - [ ] Built-ins
724 - [ ] unichr()
725 - [ ] ord()
726 - [ ] unicode() constructor
727 - [ ] Unicode type
728 - [ ] encode(), decode() methods
729 - [ ] Unicodedata module for character properties
730 - [ ] I/O
731 - [ ] Reading/writing Unicode data into files
732 - [ ] Byte-order marks
733 - [ ] Unicode filenames
734 - [ ] Writing Unicode programs
735 - [ ] Do everything in Unicode
736 - [ ] Declaring source code encodings (PEP 263)
737 - [ ] Other issues
738 - [ ] Building Python (UCS2, UCS4)