Unicode HOWTO¶
This HOWTO discusses Python’s support for the Unicode specification for representing textual data, and explains various problems that people commonly encounter when trying to work with Unicode.
Introduction to Unicode¶
Definitions¶
Today’s programs need to be able to handle a wide variety of characters. Applications are often internationalized to display messages and output in a variety of user-selectable languages; the same program might need to output an error message in English, French, Japanese, Hebrew, or Russian. Web content can be written in any of these languages and can also include a variety of emoji symbols. Python’s string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters.
Unicode (https://www.unicode.org/) is a specification that aims to list every character used by human languages and give each character its own unique code. The Unicode specifications are continually revised and updated to add new languages and symbols.
A character is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. Characters vary depending on the language or context you’re talking about. For example, there’s a character for “Roman Numeral One”, ‘Ⅰ’, that’s separate from the uppercase letter ‘I’. They’ll usually look the same, but these are two different characters that have different meanings.
The Unicode standard describes how characters are represented by code points. A code point value is an integer in the range 0 to 0x10FFFF (about 1.1 million values, the actual number assigned is less than that). In the standard and in this document, a code point is written using the notation U+265E to mean the character with value 0x265e (9,822 in decimal).
The Unicode standard contains a lot of tables listing characters and their corresponding code points:
Strictly, these definitions imply that it’s meaningless to say ‘this is character U+265E ’. U+265E is a code point, which represents some particular character; in this case, it represents the character ‘BLACK CHESS KNIGHT’, ‘♞’. In informal contexts, this distinction between code points and characters will sometimes be forgotten.
A character is represented on a screen or on paper by a set of graphical elements that’s called a glyph. The glyph for an uppercase A, for example, is two diagonal strokes and a horizontal stroke, though the exact details will depend on the font being used. Most Python code doesn’t need to worry about glyphs; figuring out the correct glyph to display is generally the job of a GUI toolkit or a terminal’s font renderer.
Encodings¶
To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a character encoding, or just an encoding.
The first encoding you might think of is using 32-bit integers as the code unit, and then using the CPU’s representation of 32-bit integers. In this representation, the string “Python” might look like this:
This representation is straightforward but using it presents a number of problems.
It’s not portable; different processors order the bytes differently.
It’s very wasteful of space. In most texts, the majority of the code points are less than 127, or less than 255, so a lot of space is occupied by 0x00 bytes. The above string takes 24 bytes compared to the 6 bytes needed for an ASCII representation. Increased RAM usage doesn’t matter too much (desktop computers have gigabytes of RAM, and strings aren’t usually that large), but expanding our usage of disk and network bandwidth by a factor of 4 is intolerable.
It’s not compatible with existing C functions such as strlen() , so a new family of wide string functions would need to be used.
Therefore this encoding isn’t used very much, and people instead choose other encodings that are more efficient and convenient, such as UTF-8.
UTF-8 is one of the most commonly used encodings, and Python often defaults to using it. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit values are used in the encoding. (There are also UTF-16 and UTF-32 encodings, but they are less frequently used than UTF-8.) UTF-8 uses the following rules:
If the code point is < 128, it’s represented by the corresponding byte value.
If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes, where each byte of the sequence is between 128 and 255.
UTF-8 has several convenient properties:
It can handle any Unicode code point.
A Unicode string is turned into a sequence of bytes that contains embedded zero bytes only where they represent the null character (U+0000). This means that UTF-8 strings can be processed by C functions such as strcpy() and sent through protocols that can’t handle zero bytes for anything other than end-of-string markers.
A string of ASCII text is also valid UTF-8 text.
UTF-8 is fairly compact; the majority of commonly used characters can be represented with one or two bytes.
If bytes are corrupted or lost, it’s possible to determine the start of the next UTF-8-encoded code point and resynchronize. It’s also unlikely that random 8-bit data will look like valid UTF-8.
UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes. This avoids the byte-ordering issues that can occur with integer and word oriented encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending on the hardware on which the string was encoded.
References¶
The Unicode Consortium site has character charts, a glossary, and PDF versions of the Unicode specification. Be prepared for some difficult reading. A chronology of the origin and development of Unicode is also available on the site.
On the Computerphile Youtube channel, Tom Scott briefly discusses the history of Unicode and UTF-8 (9 minutes 36 seconds).
To help understand the standard, Jukka Korpela has written an introductory guide to reading the Unicode character tables.
Another good introductory article was written by Joel Spolsky. If this introduction didn’t make things clear to you, you should try reading this alternate article before continuing.
Wikipedia entries are often helpful; see the entries for “character encoding” and UTF-8, for example.
Python’s Unicode Support¶
Now that you’ve learned the rudiments of Unicode, we can look at Python’s Unicode features.
The String Type¶
Since Python 3.0, the language’s str type contains Unicode characters, meaning any string created using "unicode rocks!" , ‘unicode rocks!’ , or the triple-quoted string syntax is stored as Unicode.
The default encoding for Python source code is UTF-8, so you can simply include a Unicode character in a string literal:
Side note: Python 3 also supports using Unicode characters in identifiers:
If you can’t enter a particular character in your editor or want to keep the source code ASCII-only for some reason, you can also use escape sequences in string literals. (Depending on your system, you may see the actual capital-delta glyph instead of a u escape.)
In addition, one can create a string using the decode() method of bytes . This method takes an encoding argument, such as UTF-8 , and optionally an errors argument.
The errors argument specifies the response when the input string can’t be converted according to the encoding’s rules. Legal values for this argument are ‘strict’ (raise a UnicodeDecodeError exception), ‘replace’ (use U+FFFD , REPLACEMENT CHARACTER ), ‘ignore’ (just leave the character out of the Unicode result), or ‘backslashreplace’ (inserts a \xNN escape sequence). The following examples show the differences:
Encodings are specified as strings containing the encoding’s name. Python comes with roughly 100 different encodings; see the Python Library Reference at Standard Encodings for a list. Some encodings have multiple names; for example, ‘latin-1’ , ‘iso_8859_1’ and ‘8859 ’ are all synonyms for the same encoding.
One-character Unicode strings can also be created with the chr() built-in function, which takes integers and returns a Unicode string of length 1 that contains the corresponding code point. The reverse operation is the built-in ord() function that takes a one-character Unicode string and returns the code point value:
Converting to Bytes¶
The opposite method of bytes.decode() is str.encode() , which returns a bytes representation of the Unicode string, encoded in the requested encoding.
The errors parameter is the same as the parameter of the decode() method but supports a few more possible handlers. As well as ‘strict’ , ‘ignore’ , and ‘replace’ (which in this case inserts a question mark instead of the unencodable character), there is also ‘xmlcharrefreplace’ (inserts an XML character reference), backslashreplace (inserts a \uNNNN escape sequence) and namereplace (inserts a \N <. >escape sequence).
The following example shows the different results:
The low-level routines for registering and accessing the available encodings are found in the codecs module. Implementing new encodings also requires understanding the codecs module. However, the encoding and decoding functions returned by this module are usually more low-level than is comfortable, and writing new encodings is a specialized task, so the module won’t be covered in this HOWTO.
Unicode Literals in Python Source Code¶
In Python source code, specific Unicode code points can be written using the \u escape sequence, which is followed by four hex digits giving the code point. The \U escape sequence is similar, but expects eight hex digits, not four:
Using escape sequences for code points greater than 127 is fine in small doses, but becomes an annoyance if you’re using many accented characters, as you would in a program with messages in French or some other accent-using language. You can also assemble strings using the chr() built-in function, but this is even more tedious.
Ideally, you’d want to be able to write literals in your language’s natural encoding. You could then edit Python source code with your favorite editor which would display the accented characters naturally, and have the right characters used at runtime.
Python supports writing source code in UTF-8 by default, but you can use almost any encoding if you declare the encoding being used. This is done by including a special comment as either the first or second line of the source file:
The syntax is inspired by Emacs’s notation for specifying variables local to a file. Emacs supports many different variables, but Python only supports ‘coding’. The -*- symbols indicate to Emacs that the comment is special; they have no significance to Python but are a convention. Python looks for coding: name or coding=name in the comment.
If you don’t include such a comment, the default encoding used will be UTF-8 as already mentioned. See also PEP 263 for more information.
Unicode Properties¶
The Unicode specification includes a database of information about code points. For each defined code point, the information includes the character’s name, its category, the numeric value if applicable (for characters representing numeric concepts such as the Roman numerals, fractions such as one-third and four-fifths, etc.). There are also display-related properties, such as how to use the code point in bidirectional text.
The following program displays some information about several characters, and prints the numeric value of one particular character:
When run, this prints:
The category codes are abbreviations describing the nature of the character. These are grouped into categories such as “Letter”, “Number”, “Punctuation”, or “Symbol”, which in turn are broken up into subcategories. To take the codes from the above output, ‘Ll’ means ‘Letter, lowercase’, ‘No’ means “Number, other”, ‘Mn’ is “Mark, nonspacing”, and ‘So’ is “Symbol, other”. See the General Category Values section of the Unicode Character Database documentation for a list of category codes.
Comparing Strings¶
Unicode adds some complication to comparing strings, because the same set of characters can be represented by different sequences of code points. For example, a letter like ‘ê’ can be represented as a single code point U+00EA, or as U+0065 U+0302, which is the code point for ‘e’ followed by a code point for ‘COMBINING CIRCUMFLEX ACCENT’. These will produce the same output when printed, but one is a string of length 1 and the other is of length 2.
One tool for a case-insensitive comparison is the casefold() string method that converts a string to a case-insensitive form following an algorithm described by the Unicode Standard. This algorithm has special handling for characters such as the German letter ‘ß’ (code point U+00DF), which becomes the pair of lowercase letters ‘ss’.
A second tool is the unicodedata module’s normalize() function that converts strings to one of several normal forms, where letters followed by a combining character are replaced with single characters. normalize() can be used to perform string comparisons that won’t falsely report inequality if two strings use combining characters differently:
When run, this outputs:
The first argument to the normalize() function is a string giving the desired normalization form, which can be one of ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode Standard also specifies how to do caseless comparisons:
This will print True . (Why is NFD() invoked twice? Because there are a few characters that make casefold() return a non-normalized string, so the result needs to be normalized again. See section 3.13 of the Unicode Standard for a discussion and an example.)
Unicode Regular Expressions¶
The regular expressions supported by the re module can be provided either as bytes or strings. Some of the special character sequences such as \d and \w have different meanings depending on whether the pattern is supplied as bytes or a string. For example, \d will match the characters [0-9] in bytes but in strings will match any character that’s in the ‘Nd’ category.
The string in this example has the number 57 written in both Thai and Arabic numerals:
When executed, \d+ will match the Thai numerals and print them out. If you supply the re.ASCII flag to compile() , \d+ will match the substring “57” instead.
Similarly, \w matches a wide variety of Unicode characters but only [a-zA-Z0-9_] in bytes or if re.ASCII is supplied, and \s will match either Unicode whitespace characters or [ \t\n\r\f\v] .
References¶
Some good alternative discussions of Python’s Unicode support are:
Pragmatic Unicode, a PyCon 2012 presentation by Ned Batchelder.
The str type is described in the Python library reference at Text Sequence Type — str .
The documentation for the unicodedata module.
The documentation for the codecs module.
Marc-André Lemburg gave a presentation titled “Python and Unicode” (PDF slides) at EuroPython 2002. The slides are an excellent overview of the design of Python 2’s Unicode features (where the Unicode string type is called unicode and literals start with u ).
Reading and Writing Unicode Data¶
Once you’ve written some code that works with Unicode data, the next problem is input/output. How do you get Unicode strings into your program, and how do you convert Unicode into a form suitable for storage or transmission?
It’s possible that you may not need to do anything depending on your input sources and output destinations; you should check whether the libraries used in your application support Unicode natively. XML parsers often return Unicode data, for example. Many relational databases also support Unicode-valued columns and can return Unicode values from an SQL query.
Unicode data is usually converted to a particular encoding before it gets written to disk or sent over a socket. It’s possible to do all the work yourself: open a file, read an 8-bit bytes object from it, and convert the bytes with bytes.decode(encoding) . However, the manual approach is not recommended.
One problem is the multi-byte nature of encodings; one Unicode character can be represented by several bytes. If you want to read the file in arbitrary-sized chunks (say, 1024 or 4096 bytes), you need to write error-handling code to catch the case where only part of the bytes encoding a single Unicode character are read at the end of a chunk. One solution would be to read the entire file into memory and then perform the decoding, but that prevents you from working with files that are extremely large; if you need to read a 2 GiB file, you need 2 GiB of RAM. (More, really, since for at least a moment you’d need to have both the encoded string and its Unicode version in memory.)
The solution would be to use the low-level decoding interface to catch the case of partial coding sequences. The work of implementing this has already been done for you: the built-in open() function can return a file-like object that assumes the file’s contents are in a specified encoding and accepts Unicode parameters for methods such as read() and write() . This works through open() ‘s encoding and errors parameters which are interpreted just like those in str.encode() and bytes.decode() .
Reading Unicode from a file is therefore simple:
It’s also possible to open files in update mode, allowing both reading and writing:
The Unicode character U+FEFF is used as a byte-order mark (BOM), and is often written as the first character of a file in order to assist with autodetection of the file’s byte ordering. Some encodings, such as UTF-16, expect a BOM to be present at the start of a file; when such an encoding is used, the BOM will be automatically written as the first character and will be silently dropped when the file is read. There are variants of these encodings, such as ‘utf-16-le’ and ‘utf-16-be’ for little-endian and big-endian encodings, that specify one particular byte ordering and don’t skip the BOM.
In some areas, it is also convention to use a “BOM” at the start of UTF-8 encoded files; the name is misleading since UTF-8 is not byte-order dependent. The mark simply announces that the file is encoded in UTF-8. For reading such files, use the ‘utf-8-sig’ codec to automatically skip the mark if present.
Unicode filenames¶
Most of the operating systems in common use today support filenames that contain arbitrary Unicode characters. Usually this is implemented by converting the Unicode string into some encoding that varies depending on the system. Today Python is converging on using UTF-8: Python on MacOS has used UTF-8 for several versions, and Python 3.6 switched to using UTF-8 on Windows as well. On Unix systems, there will only be a filesystem encoding . if you’ve set the LANG or LC_CTYPE environment variables; if you haven’t, the default encoding is again UTF-8.
The sys.getfilesystemencoding() function returns the encoding to use on your current system, in case you want to do the encoding manually, but there’s not much reason to bother. When opening a file for reading or writing, you can usually just provide the Unicode string as the filename, and it will be automatically converted to the right encoding for you:
Functions in the os module such as os.stat() will also accept Unicode filenames.
The os.listdir() function returns filenames, which raises an issue: should it return the Unicode version of filenames, or should it return bytes containing the encoded versions? os.listdir() can do both, depending on whether you provided the directory path as bytes or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem’s encoding and a list of Unicode strings will be returned, while passing a byte path will return the filenames as bytes. For example, assuming the default filesystem encoding is UTF-8, running the following program:
will produce the following output:
The first list contains UTF-8-encoded filenames, and the second list contains the Unicode versions.
Note that on most occasions, you should can just stick with using Unicode with these APIs. The bytes APIs should only be used on systems where undecodable file names can be present; that’s pretty much only Unix systems now.
Tips for Writing Unicode-aware Programs¶
This section provides some suggestions on writing software that deals with Unicode.
The most important tip is:
Software should only work with Unicode strings internally, decoding the input data as soon as possible and encoding the output only at the end.
If you attempt to write processing functions that accept both Unicode and byte strings, you will find your program vulnerable to bugs wherever you combine the two different kinds of strings. There is no automatic encoding or decoding: if you do e.g. str + bytes , a TypeError will be raised.
When using data coming from a web browser or some other untrusted source, a common technique is to check for illegal characters in a string before using the string in a generated command line or storing it in a database. If you’re doing this, be careful to check the decoded string, not the encoded bytes data; some encodings may have interesting properties, such as not being bijective or not being fully ASCII-compatible. This is especially true if the input data also specifies the encoding, since the attacker can then choose a clever way to hide malicious text in the encoded bytestream.
Converting Between File Encodings¶
The StreamRecoder class can transparently convert between encodings, taking a stream that returns data in encoding #1 and behaving like a stream returning data in encoding #2.
For example, if you have an input file f that’s in Latin-1, you can wrap it with a StreamRecoder to return bytes encoded in UTF-8:
Files in an Unknown Encoding¶
What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:
The surrogateescape error handler will decode any non-ASCII bytes as code points in a special range running from U+DC80 to U+DCFF. These code points will then turn back into the same bytes when the surrogateescape error handler is used to encode the data and write it back out.
References¶
One section of Mastering Python 3 Input/Output, a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling.
The PDF slides for Marc-André Lemburg’s presentation “Writing Unicode-aware Applications in Python” discuss questions of character encodings as well as how to internationalize and localize an application. These slides cover Python 2.x only.
The Guts of Unicode in Python is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode representation in Python 3.3.
Acknowledgements¶
The initial draft of this document was written by Andrew Kuchling. It has since been revised further by Alexander Belopolsky, Georg Brandl, Andrew Kuchling, and Ezio Melotti.
Thanks to the following people who have noted errors or offered suggestions on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, Eryk Sun, Chad Whitacre, Graham Wideman.
Unicode in Python
Different machines used different encodings – different ways of mapping the binary data that the computer stores to letters.
Then there was ASCII – and all was good (7 bit), 127 characters
(for English speakers, anyway)
But each vendor used the top half of 8bit bytes (127-255) for different things.
MacRoman, Windows 1252, etc…
There is now “latin-1”, a 1-byte encoding suitable for European languages – but still a lot of old files around that use the old ones.
Non-Western European languages required totally incompatible 1-byte encodings
This means there was no way to mix languages with different alphabets in the same document (web page, etc.)
Enter Unicode
One “code point” for all characters in all languages
Early days: we can fit all the code points in a two byte integer (65536 characters)
Turns out that didn’t work – 65536 is not enough for all languages. So we now need 32 bit integer to hold all of Unicode “raw” (UTC-4).
But it’s a waste of space to use 4 full bytes for each character, when so many don’t require that much space.
An encoding is a way to map specific bytes to a code point.
Each code point can be represented by one or more bytes.
Each encoding is different – if you don’t know the encoding, you don’t know how to interpret the bytes! (though maybe you can guess)
Unicode
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Everything is Bytes
If it’s on disk or on a network, it’s bytes
Python provides some abstractions to make it easier to deal with bytes
Unicode is a Biggie
Actually, dealing with numbers rather than bytes is big
– but we take that for granted.
Mechanics
What are strings?
Py2 strings were simply sequences of bytes. When text was one per character that worked fine.
Py3 strings (or Unicode strings in py2) are sequences of “platonic characters”.
It’s almost one code point per character – there are complications with combined characters: accents, etc – but we can mostly ignore those – you will get far thinking of a code point as a character.
Platonic characters cannot be written to disk or network!
(ANSI: one character == one byte – it was so easy!)
Strings vs Unicode
Python 2 had two types that let you work with text:
And two ways to work with binary data:
bytes() (and bytearray )
but:
bytes is there in py2 for py3 compatibility – but it’s good for making your intentions clear, too.
py3 is more clear:
str for text bytes for binary data
Unicode
The py3 string (py2 Unicode ) object lets you work with characters, instead of bytes.
It has all the same methods you’d expect a string object to have.
Encoding / Decoding
If you need to deal with the actual bytes for some reason, you may need to convert between a string object and a particular set of bytes.
“encoding” is converting from a string object to bytes
“decoding” is converting from bytes to a string object
(sometimes this feels backwards…)
And can get even more confusing with py2 strings being both text and bytes!
This is actually one of the biggest differences between Python 2 and Python 3. As an ordinary user (particularly one that used English…), you may not notice – text is text, and things generally “just work”, but under the hood it is very different, and folks writting libraries for things like Internet protocols struggled with the differences.
Using Unicode in Py2
If you do need to write Python2 code, you really should use Unicode. If you don’t – skip ahead to “Unicode Literals”.
codecs — Codec registry and base classes¶
This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are text encodings , which encode text to bytes (and decode bytes to text), but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to be used specifically with text encodings or with codecs that encode to bytes .
The module defines the following functions for encoding and decoding with any codec:
codecs. encode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶
Encodes obj using the codec registered for encoding.
Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError ). Refer to Codec Base Classes for more information on codec error handling.
codecs. decode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶
Decodes obj using the codec registered for encoding.
Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError ). Refer to Codec Base Classes for more information on codec error handling.
The full details for each codec can also be looked up directly:
codecs. lookup ( encoding ) ¶
Looks up the codec info in the Python codec registry and returns a CodecInfo object as defined below.
Encodings are first looked up in the registry’s cache. If not found, the list of registered search functions is scanned. If no CodecInfo object is found, a LookupError is raised. Otherwise, the CodecInfo object is stored in the cache and returned to the caller.
class codecs. CodecInfo ( encode , decode , streamreader = None , streamwriter = None , incrementalencoder = None , incrementaldecoder = None , name = None ) ¶
Codec details when looking up the codec registry. The constructor arguments are stored in attributes of the same name:
The name of the encoding.
The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the encode() and decode() methods of Codec instances (see Codec Interface ). The functions or methods are expected to work in a stateless mode.
Incremental encoder and decoder classes or factory functions. These have to provide the interface defined by the base classes IncrementalEncoder and IncrementalDecoder , respectively. Incremental codecs can maintain state.
Stream writer and reader classes or factory functions. These have to provide the interface defined by the base classes StreamWriter and StreamReader , respectively. Stream codecs can maintain state.
To simplify access to the various codec components, the module provides these additional functions which use lookup() for the codec lookup:
codecs. getencoder ( encoding ) ¶
Look up the codec for the given encoding and return its encoder function.
Raises a LookupError in case the encoding cannot be found.
codecs. getdecoder ( encoding ) ¶
Look up the codec for the given encoding and return its decoder function.
Raises a LookupError in case the encoding cannot be found.
codecs. getincrementalencoder ( encoding ) ¶
Look up the codec for the given encoding and return its incremental encoder class or factory function.
Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental encoder.
codecs. getincrementaldecoder ( encoding ) ¶
Look up the codec for the given encoding and return its incremental decoder class or factory function.
Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental decoder.
codecs. getreader ( encoding ) ¶
Look up the codec for the given encoding and return its StreamReader class or factory function.
Raises a LookupError in case the encoding cannot be found.
codecs. getwriter ( encoding ) ¶
Look up the codec for the given encoding and return its StreamWriter class or factory function.
Raises a LookupError in case the encoding cannot be found.
Custom codecs are made available by registering a suitable codec search function:
codecs. register ( search_function ) ¶
Register a codec search function. Search functions are expected to take one argument, being the encoding name in all lower case letters with hyphens and spaces converted to underscores, and return a CodecInfo object. In case a search function cannot find a given encoding, it should return None .
Changed in version 3.9: Hyphens and spaces are converted to underscore.
Unregister a codec search function and clear the registry’s cache. If the search function is not registered, do nothing.
New in version 3.10.
While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files:
codecs. open ( filename , mode = ‘r’ , encoding = None , errors = ‘strict’ , buffering = — 1 ) ¶
Open an encoded file using the given mode and return an instance of StreamReaderWriter , providing transparent encoding/decoding. The default file mode is ‘r’ , meaning to open the file in read mode.
If encoding is not None , then the underlying encoded files are always opened in binary mode. No automatic conversion of ‘\n’ is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in open() function; the ‘b’ is automatically added.
encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used.
errors may be given to define the error handling. It defaults to ‘strict’ which causes a ValueError to be raised in case an encoding error occurs.
buffering has the same meaning as for the built-in open() function. It defaults to -1 which means that the default buffer size will be used.
Changed in version 3.11: The ‘U’ mode has been removed.
Return a StreamRecoder instance, a wrapped version of file which provides transparent transcoding. The original file is closed when the wrapped version is closed.
Data written to the wrapped file is decoded according to the given data_encoding and then written to the original file as bytes using file_encoding. Bytes read from the original file are decoded according to file_encoding, and the result is encoded using data_encoding.
If file_encoding is not given, it defaults to data_encoding.
errors may be given to define the error handling. It defaults to ‘strict’ , which causes ValueError to be raised in case an encoding error occurs.
codecs. iterencode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶
Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental encoder.
This function requires that the codec accept text str objects to encode. Therefore it does not support bytes-to-bytes encoders such as base64_codec .
codecs. iterdecode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶
Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental decoder.
This function requires that the codec accept bytes objects to decode. Therefore it does not support text-to-text encoders such as rot_13 , although rot_13 may be used equivalently with iterencode() .
The module also provides the following constants which are useful for reading and writing to platform dependent files:
codecs. BOM ¶ codecs. BOM_BE ¶ codecs. BOM_LE ¶ codecs. BOM_UTF8 ¶ codecs. BOM_UTF16 ¶ codecs. BOM_UTF16_BE ¶ codecs. BOM_UTF16_LE ¶ codecs. BOM_UTF32 ¶ codecs. BOM_UTF32_BE ¶ codecs. BOM_UTF32_LE ¶
These constants define various byte sequences, being Unicode byte order marks (BOMs) for several encodings. They are used in UTF-16 and UTF-32 data streams to indicate the byte order used, and in UTF-8 as a Unicode signature. BOM_UTF16 is either BOM_UTF16_BE or BOM_UTF16_LE depending on the platform’s native byte order, BOM is an alias for BOM_UTF16 , BOM_LE for BOM_UTF16_LE and BOM_BE for BOM_UTF16_BE . The others represent the BOM in UTF-8 and UTF-32 encodings.
Codec Base Classes¶
The codecs module defines a set of base classes which define the interfaces for working with codec objects, and can also be used as the basis for custom codec implementations.
Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors.
Error Handlers¶
To simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument:
The following error handlers can be used with all Python Standard Encodings codecs:
Raise UnicodeError (or a subclass), this is the default. Implemented in strict_errors() .
Ignore the malformed data and continue without further notice. Implemented in ignore_errors() .
Replace with a replacement marker. On encoding, use ? (ASCII character). On decoding, use � (U+FFFD, the official REPLACEMENT CHARACTER). Implemented in replace_errors() .
Replace with backslashed escape sequences. On encoding, use hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use hexadecimal form of byte value with format \xhh . Implemented in backslashreplace_errors() .
On decoding, replace byte with individual surrogate code ranging from U+DC80 to U+DCFF . This code will then be turned back into the same byte when the ‘surrogateescape’ error handler is used when encoding the data. (See PEP 383 for more.)
The following error handlers are only applicable to encoding (within text encodings ):
Replace with XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; Implemented in xmlcharrefreplace_errors() .
Replace with \N <. >escape sequences, what appears in the braces is the Name property from Unicode Character Database. Implemented in namereplace_errors() .
In addition, the following error handler is specific to the given codecs:
utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le
Allow encoding and decoding surrogate code point ( U+D800 — U+DFFF ) as normal code point. Otherwise these codecs treat the presence of surrogate code point in str as an error.
New in version 3.1: The ‘surrogateescape’ and ‘surrogatepass’ error handlers.
Changed in version 3.4: The ‘surrogatepass’ error handler now works with utf-16* and utf-32* codecs.
New in version 3.5: The ‘namereplace’ error handler.
Changed in version 3.5: The ‘backslashreplace’ error handler now works with decoding and translating.
The set of allowed values can be extended by registering a new named error handler:
codecs. register_error ( name , error_handler ) ¶
Register the error handling function error_handler under the name name. The error_handler argument will be called during encoding and decoding in case of an error, when name is specified as the errors parameter.
For encoding, error_handler will be called with a UnicodeEncodeError instance, which contains information about the location of the error. The error handler must either raise this or a different exception, or return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue. The replacement may be either str or bytes . If the replacement is bytes, the encoder will simply copy them into the output buffer. If the replacement is a string, the encoder will encode the replacement. Encoding continues on original input at the specified position. Negative position values will be treated as being relative to the end of the input string. If the resulting position is out of bound an IndexError will be raised.
Decoding and translating works similarly, except UnicodeDecodeError or UnicodeTranslateError will be passed to the handler and that the replacement from the error handler will be put into the output directly.
Previously registered error handlers (including the standard error handlers) can be looked up by name:
codecs. lookup_error ( name ) ¶
Return the error handler previously registered under the name name.
Raises a LookupError in case the handler cannot be found.
The following standard error handlers are also made available as module level functions:
codecs. strict_errors ( exception ) ¶
Implements the ‘strict’ error handling.
Each encoding or decoding error raises a UnicodeError .
codecs. ignore_errors ( exception ) ¶
Implements the ‘ignore’ error handling.
Malformed data is ignored; encoding or decoding is continued without further notice.
codecs. replace_errors ( exception ) ¶
Implements the ‘replace’ error handling.
Substitutes ? (ASCII character) for encoding errors or � (U+FFFD, the official REPLACEMENT CHARACTER) for decoding errors.
codecs. backslashreplace_errors ( exception ) ¶
Implements the ‘backslashreplace’ error handling.
Malformed data is replaced by a backslashed escape sequence. On encoding, use the hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use the hexadecimal form of byte value with format \xhh .
Changed in version 3.5: Works with decoding and translating.
Implements the ‘xmlcharrefreplace’ error handling (for encoding within text encoding only).
The unencodable character is replaced by an appropriate XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; .
codecs. namereplace_errors ( exception ) ¶
Implements the ‘namereplace’ error handling (for encoding within text encoding only).
The unencodable character is replaced by a \N <. >escape sequence. The set of characters that appear in the braces is the Name property from Unicode Character Database. For example, the German lowercase letter ‘ß’ will be converted to byte sequence \N
New in version 3.5.
Stateless Encoding and Decoding¶
The base Codec class defines these methods which also define the function interfaces of the stateless encoder and decoder:
Codec. encode ( input , errors = ‘strict’ ) ¶
Encodes the object input and returns a tuple (output object, length consumed). For instance, text encoding converts a string object to a bytes object using a particular character set encoding (e.g., cp1252 or iso-8859-1 ).
The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.
The method may not store state in the Codec instance. Use StreamWriter for codecs which have to keep state in order to make encoding efficient.
The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.
Codec. decode ( input , errors = ‘strict’ ) ¶
Decodes the object input and returns a tuple (output object, length consumed). For instance, for a text encoding , decoding converts a bytes object encoded using a particular character set encoding to a string object.
For text encodings and bytes-to-bytes codecs, input must be a bytes object or one which provides the read-only buffer interface – for example, buffer objects and memory mapped files.
The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.
The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient.
The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.
Incremental Encoding and Decoding¶
The IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode() / decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.
The joined output of calls to the encode() / decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.
IncrementalEncoder Objects¶
The IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry.
class codecs. IncrementalEncoder ( errors = ‘strict’ ) ¶
Constructor for an IncrementalEncoder instance.
All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.
The IncrementalEncoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.
The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalEncoder object.
encode ( object , final = False ) ¶
Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to encode() final must be true (the default is false).
Reset the encoder to the initial state. The output is discarded: call .encode(object, final=True) , passing an empty byte or text string if necessary, to reset the encoder and to get the output.
Return the current state of the encoder which must be an integer. The implementation should make sure that 0 is the most common state. (States that are more complicated than integers can be converted into an integer by marshaling/pickling the state and encoding the bytes of the resulting string into an integer.)
Set the state of the encoder to state. state must be an encoder state returned by getstate() .
IncrementalDecoder Objects¶
The IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define in order to be compatible with the Python codec registry.
class codecs. IncrementalDecoder ( errors = ‘strict’ ) ¶
Constructor for an IncrementalDecoder instance.
All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.
The IncrementalDecoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.
The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalDecoder object.
decode ( object , final = False ) ¶
Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to decode() final must be true (the default is false). If final is true the decoder must decode the input completely and must flush all buffers. If this isn’t possible (e.g. because of incomplete byte sequences at the end of the input) it must initiate error handling just like in the stateless case (which might raise an exception).
Reset the decoder to the initial state.
Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that 0 is the most common additional state info.) If this additional state info is 0 it must be possible to set the decoder to the state which has no input buffered and 0 as the additional state info, so that feeding the previously buffered input to the decoder returns it to the previous state without producing any output. (Additional state info that is more complicated than integers can be converted into an integer by marshaling/pickling the info and encoding the bytes of the resulting string into an integer.)
Set the state of the decoder to state. state must be a decoder state returned by getstate() .
Stream Encoding and Decoding¶
The StreamWriter and StreamReader classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.
StreamWriter Objects¶
The StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define in order to be compatible with the Python codec registry.
class codecs. StreamWriter ( stream , errors = ‘strict’ ) ¶
Constructor for a StreamWriter instance.
All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.
The stream argument must be a file-like object open for writing text or binary data, as appropriate for the specific codec.
The StreamWriter may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.
The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamWriter object.
Writes the object’s contents encoded to the stream.
Writes the concatenated iterable of strings to the stream (possibly by reusing the write() method). Infinite or very large iterables are not supported. The standard bytes-to-bytes codecs do not support this method.
Resets the codec buffers used for keeping internal state.
Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state.
In addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.
StreamReader Objects¶
The StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define in order to be compatible with the Python codec registry.
class codecs. StreamReader ( stream , errors = ‘strict’ ) ¶
Constructor for a StreamReader instance.
All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.
The stream argument must be a file-like object open for reading text or binary data, as appropriate for the specific codec.
The StreamReader may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.
The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamReader object.
The set of allowed values for the errors argument can be extended with register_error() .
read ( size = — 1 , chars = — 1 , firstline = False ) ¶
Decodes data from the stream and returns the resulting object.
The chars argument indicates the number of decoded code points or bytes to return. The read() method will never return more data than requested, but it might return less, if there is not enough available.
The size argument indicates the approximate maximum number of encoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. This parameter is intended to prevent having to decode huge files in one step.
The firstline flag indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines.
The method should use a greedy read strategy meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too.
readline ( size = None , keepends = True ) ¶
Read one line from the input stream and return the decoded data.
size, if given, is passed as size argument to the stream’s read() method.
If keepends is false line-endings will be stripped from the lines returned.
readlines ( sizehint = None , keepends = True ) ¶
Read all lines available on the input stream and return them as a list of lines.
Line-endings are implemented using the codec’s decode() method and are included in the list entries if keepends is true.
sizehint, if given, is passed as the size argument to the stream’s read() method.
Resets the codec buffers used for keeping internal state.
Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
In addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.
StreamReaderWriter Objects¶
The StreamReaderWriter is a convenience class that allows wrapping streams which work in both read and write modes.
The design is such that one can use the factory functions returned by the lookup() function to construct the instance.
class codecs. StreamReaderWriter ( stream , Reader , Writer , errors = ‘strict’ ) ¶
Creates a StreamReaderWriter instance. stream must be a file-like object. Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interface resp. Error handling is done in the same way as defined for the stream readers and writers.
StreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.
StreamRecoder Objects¶
The StreamRecoder translates data from one encoding to another, which is sometimes useful when dealing with different encoding environments.
The design is such that one can use the factory functions returned by the lookup() function to construct the instance.
class codecs. StreamRecoder ( stream , encode , decode , Reader , Writer , errors = ‘strict’ ) ¶
Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend — the data visible to code calling read() and write() , while Reader and Writer work on the backend — the data in stream.
You can use these objects to do transparent transcodings, e.g., from Latin-1 to UTF-8 and back.
The stream argument must be a file-like object.
The encode and decode arguments must adhere to the Codec interface. Reader and Writer must be factory functions or classes providing objects of the StreamReader and StreamWriter interface respectively.
Error handling is done in the same way as defined for the stream readers and writers.
StreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.
Encodings and Unicode¶
Strings are stored internally as sequences of code points in range U+0000 – U+10FFFF . (See PEP 393 for more details about the implementation.) Once a string object is used outside of CPU and memory, endianness and how these arrays are stored as bytes become an issue. As with other codecs, serialising a string into a sequence of bytes is known as encoding, and recreating the string from the sequence of bytes is known as decoding. There are a variety of different text serialisation codecs, which are collectivity referred to as text encodings .
The simplest text encoding (called ‘latin-1’ or ‘iso-8859-1’ ) maps the code points 0–255 to the bytes 0x0 – 0xff , which means that a string object that contains code points above U+00FF can’t be encoded with this codec. Doing so will raise a UnicodeEncodeError that looks like the following (although the details of the error message may differ): UnicodeEncodeError: ‘latin-1’ codec can’t encode character ‘\u1234’ in position 3: ordinal not in range(256) .
There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0 – 0xff . To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.
All of these encodings can only encode 256 of the 1114112 code points defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each code point as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These two encodings are called UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if e.g. you use UTF-32-BE on a little endian machine you will always have to swap bytes on encoding and decoding. UTF-32 avoids this problem: bytes will always be in natural endianness. When these bytes are read by a CPU with a different endianness, then bytes have to be swapped though. To be able to detect the endianness of a UTF-16 or UTF-32 byte sequence, there’s the so called BOM (“Byte Order Mark”). This is the Unicode character U+FEFF . This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character ( 0xFFFE ) is an illegal character that may not appear in a Unicode text. So when the first character in a UTF-16 or UTF-32 byte sequence appears to be a U+FFFE the bytes have to be swapped on decoding. Unfortunately the character U+FEFF had a second purpose as a ZERO WIDTH NO-BREAK SPACE : a character that has no width and doesn’t allow a word to be split. It can e.g. be used to give hints to a ligature algorithm. With Unicode 4.0 using U+FEFF as a ZERO WIDTH NO-BREAK SPACE has been deprecated (with U+2060 ( WORD JOINER ) assuming this role). Nevertheless Unicode software still must be able to handle U+FEFF in both roles: as a BOM it’s a device to determine the storage layout of the encoded bytes, and vanishes once the byte sequence has been decoded into a string; as a ZERO WIDTH NO-BREAK SPACE it’s a normal character that will be decoded like any other.
There’s another encoding that is able to encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):
Unicode HOWTO¶
This HOWTO discusses Python support for Unicode, and explains various problems that people commonly encounter when trying to work with Unicode.
Introduction to Unicode¶
History of Character Codes¶
In 1968, the American Standard Code for Information Interchange, better known by its acronym ASCII, was standardized. ASCII defined numeric codes for various characters, with the numeric values running from 0 to 127. For example, the lowercase letter ‘a’ is assigned 97 as its code value.
ASCII was an American-developed standard, so it only defined unaccented characters. There was an ‘e’, but no ‘é’ or ‘Í’. This meant that languages which required accented characters couldn’t be faithfully represented in ASCII. (Actually the missing accents matter for English, too, which contains words such as ‘naïve’ and ‘café’, and some publications have house styles which require spellings such as ‘coöperate’.)
For a while people just wrote programs that didn’t display accents. In the mid-1980s an Apple II BASIC program written by a French speaker might have lines like these:
Those messages should contain accents (terminée, paramètre, enregistrés) and they just look wrong to someone who can read French.
In the 1980s, almost all personal computers were 8-bit, meaning that bytes could hold values ranging from 0 to 255. ASCII codes only went up to 127, so some machines assigned values between 128 and 255 to accented characters. Different machines had different codes, however, which led to problems exchanging files. Eventually various commonly used sets of values for the 128–255 range emerged. Some were true standards, defined by the International Organization for Standardization, and some were de facto conventions that were invented by one company or another and managed to catch on.
255 characters aren’t very many. For example, you can’t fit both the accented characters used in Western Europe and the Cyrillic alphabet used for Russian into the 128–255 range because there are more than 128 such characters.
You could write files using different codes (all your Russian files in a coding system called KOI8, all your French files in a different coding system called Latin1), but what if you wanted to write a French document that quotes some Russian text? In the 1980s people began to want to solve this problem, and the Unicode standardization effort began.
Unicode started out using 16-bit characters instead of 8-bit characters. 16 bits means you have 2^16 = 65,536 distinct values available, making it possible to represent many different characters from many different alphabets; an initial goal was to have Unicode contain the alphabets for every single human language. It turns out that even 16 bits isn’t enough to meet that goal, and the modern Unicode specification uses a wider range of codes, 0 through 1,114,111 ( 0x10FFFF in base 16).
There’s a related ISO standard, ISO 10646. Unicode and ISO 10646 were originally separate efforts, but the specifications were merged with the 1.1 revision of Unicode.
(This discussion of Unicode’s history is highly simplified. The precise historical details aren’t necessary for understanding how to use Unicode effectively, but if you’re curious, consult the Unicode consortium site listed in the References or the Wikipedia entry for Unicode for more information.)
Definitions¶
A character is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. Characters are abstractions, and vary depending on the language or context you’re talking about. For example, the symbol for ohms (Ω) is usually drawn much like the capital letter omega (Ω) in the Greek alphabet (they may even be the same in some fonts), but these are two different characters that have different meanings.
The Unicode standard describes how characters are represented by code points. A code point is an integer value, usually denoted in base 16. In the standard, a code point is written using the notation U+12CA to mean the character with value 0x12ca (4,810 decimal). The Unicode standard contains a lot of tables listing characters and their corresponding code points:
Strictly, these definitions imply that it’s meaningless to say ‘this is character U+12CA ‘. U+12CA is a code point, which represents some particular character; in this case, it represents the character ‘ETHIOPIC SYLLABLE WI’. In informal contexts, this distinction between code points and characters will sometimes be forgotten.
A character is represented on a screen or on paper by a set of graphical elements that’s called a glyph. The glyph for an uppercase A, for example, is two diagonal strokes and a horizontal stroke, though the exact details will depend on the font being used. Most Python code doesn’t need to worry about glyphs; figuring out the correct glyph to display is generally the job of a GUI toolkit or a terminal’s font renderer.
Encodings¶
To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence needs to be represented as a set of bytes (meaning, values from 0 through 255) in memory. The rules for translating a Unicode string into a sequence of bytes are called an encoding.
The first encoding you might think of is an array of 32-bit integers. In this representation, the string “Python” would look like this:
This representation is straightforward but using it presents a number of problems.
- It’s not portable; different processors order the bytes differently.
- It’s very wasteful of space. In most texts, the majority of the code points are less than 127, or less than 255, so a lot of space is occupied by 0x00 bytes. The above string takes 24 bytes compared to the 6 bytes needed for an ASCII representation. Increased RAM usage doesn’t matter too much (desktop computers have gigabytes of RAM, and strings aren’t usually that large), but expanding our usage of disk and network bandwidth by a factor of 4 is intolerable.
- It’s not compatible with existing C functions such as strlen() , so a new family of wide string functions would need to be used.
- Many Internet standards are defined in terms of textual data, and can’t handle content with embedded zero bytes.
Generally people don’t use this encoding, instead choosing other encodings that are more efficient and convenient. UTF-8 is probably the most commonly supported encoding; it will be discussed below.
Encodings don’t have to handle every possible Unicode character, and most encodings don’t. The rules for converting a Unicode string into the ASCII encoding, for example, are simple; for each code point:
- If the code point is < 128, each byte is the same as the value of the code point.
- If the code point is 128 or greater, the Unicode string can’t be represented in this encoding. (Python raises a UnicodeEncodeError exception in this case.)
Latin-1, also known as ISO-8859-1, is a similar encoding. Unicode code points 0–255 are identical to the Latin-1 values, so converting to this encoding simply requires converting code points to byte values; if a code point larger than 255 is encountered, the string can’t be encoded into Latin-1.
Encodings don’t have to be simple one-to-one mappings like Latin-1. Consider IBM’s EBCDIC, which was used on IBM mainframes. Letter values weren’t in one block: ‘a’ through ‘i’ had values from 129 to 137, but ‘j’ through ‘r’ were 145 through 153. If you wanted to use EBCDIC as an encoding, you’d probably use some sort of lookup table to perform the conversion, but this is largely an internal detail.
UTF-8 is one of the most commonly used encodings. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit numbers are used in the encoding. (There are also a UTF-16 and UTF-32 encodings, but they are less frequently used than UTF-8.) UTF-8 uses the following rules:
- If the code point is < 128, it’s represented by the corresponding byte value.
- If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes, where each byte of the sequence is between 128 and 255.
UTF-8 has several convenient properties:
- It can handle any Unicode code point.
- A Unicode string is turned into a sequence of bytes containing no embedded zero bytes. This avoids byte-ordering issues, and means UTF-8 strings can be processed by C functions such as strcpy() and sent through protocols that can’t handle zero bytes.
- A string of ASCII text is also valid UTF-8 text.
- UTF-8 is fairly compact; the majority of commonly used characters can be represented with one or two bytes.
- If bytes are corrupted or lost, it’s possible to determine the start of the next UTF-8-encoded code point and resynchronize. It’s also unlikely that random 8-bit data will look like valid UTF-8.
References¶
The Unicode Consortium site has character charts, a glossary, and PDF versions of the Unicode specification. Be prepared for some difficult reading. A chronology of the origin and development of Unicode is also available on the site.
To help understand the standard, Jukka Korpela has written an introductory guide to reading the Unicode character tables.
Another good introductory article was written by Joel Spolsky. If this introduction didn’t make things clear to you, you should try reading this alternate article before continuing.
Wikipedia entries are often helpful; see the entries for “character encoding” and UTF-8, for example.
Python’s Unicode Support¶
Now that you’ve learned the rudiments of Unicode, we can look at Python’s Unicode features.
The String Type¶
Since Python 3.0, the language features a str type that contain Unicode characters, meaning any string created using "unicode rocks!" , ‘unicode rocks!’ , or the triple-quoted string syntax is stored as Unicode.
The default encoding for Python source code is UTF-8, so you can simply include a Unicode character in a string literal:
You can use a different encoding from UTF-8 by putting a specially-formatted comment as the first or second line of the source code:
Side note: Python 3 also supports using Unicode characters in identifiers:
If you can’t enter a particular character in your editor or want to keep the source code ASCII-only for some reason, you can also use escape sequences in string literals. (Depending on your system, you may see the actual capital-delta glyph instead of a u escape.)
In addition, one can create a string using the decode() method of bytes . This method takes an encoding argument, such as UTF-8 , and optionally an errors argument.
The errors argument specifies the response when the input string can’t be converted according to the encoding’s rules. Legal values for this argument are ‘strict’ (raise a UnicodeDecodeError exception), ‘replace’ (use U+FFFD , REPLACEMENT CHARACTER ), ‘ignore’ (just leave the character out of the Unicode result), or ‘backslashreplace’ (inserts a \xNN escape sequence). The following examples show the differences:
Encodings are specified as strings containing the encoding’s name. Python 3.2 comes with roughly 100 different encodings; see the Python Library Reference at Standard Encodings for a list. Some encodings have multiple names; for example, ‘latin-1’ , ‘iso_8859_1’ and ‘8859 ‘ are all synonyms for the same encoding.
One-character Unicode strings can also be created with the chr() built-in function, which takes integers and returns a Unicode string of length 1 that contains the corresponding code point. The reverse operation is the built-in ord() function that takes a one-character Unicode string and returns the code point value:
Converting to Bytes¶
The opposite method of bytes.decode() is str.encode() , which returns a bytes representation of the Unicode string, encoded in the requested encoding.
The errors parameter is the same as the parameter of the decode() method but supports a few more possible handlers. As well as ‘strict’ , ‘ignore’ , and ‘replace’ (which in this case inserts a question mark instead of the unencodable character), there is also ‘xmlcharrefreplace’ (inserts an XML character reference), backslashreplace (inserts a \uNNNN escape sequence) and namereplace (inserts a \N <. >escape sequence).
The following example shows the different results:
The low-level routines for registering and accessing the available encodings are found in the codecs module. Implementing new encodings also requires understanding the codecs module. However, the encoding and decoding functions returned by this module are usually more low-level than is comfortable, and writing new encodings is a specialized task, so the module won’t be covered in this HOWTO.
Unicode Literals in Python Source Code¶
In Python source code, specific Unicode code points can be written using the \u escape sequence, which is followed by four hex digits giving the code point. The \U escape sequence is similar, but expects eight hex digits, not four:
Using escape sequences for code points greater than 127 is fine in small doses, but becomes an annoyance if you’re using many accented characters, as you would in a program with messages in French or some other accent-using language. You can also assemble strings using the chr() built-in function, but this is even more tedious.
Ideally, you’d want to be able to write literals in your language’s natural encoding. You could then edit Python source code with your favorite editor which would display the accented characters naturally, and have the right characters used at runtime.
Python supports writing source code in UTF-8 by default, but you can use almost any encoding if you declare the encoding being used. This is done by including a special comment as either the first or second line of the source file:
The syntax is inspired by Emacs’s notation for specifying variables local to a file. Emacs supports many different variables, but Python only supports ‘coding’. The -*- symbols indicate to Emacs that the comment is special; they have no significance to Python but are a convention. Python looks for coding: name or coding=name in the comment.
If you don’t include such a comment, the default encoding used will be UTF-8 as already mentioned. See also PEP 263 for more information.
Unicode Properties¶
The Unicode specification includes a database of information about code points. For each defined code point, the information includes the character’s name, its category, the numeric value if applicable (Unicode has characters representing the Roman numerals and fractions such as one-third and four-fifths). There are also properties related to the code point’s use in bidirectional text and other display-related properties.
The following program displays some information about several characters, and prints the numeric value of one particular character:
When run, this prints:
The category codes are abbreviations describing the nature of the character. These are grouped into categories such as “Letter”, “Number”, “Punctuation”, or “Symbol”, which in turn are broken up into subcategories. To take the codes from the above output, ‘Ll’ means ‘Letter, lowercase’, ‘No’ means “Number, other”, ‘Mn’ is “Mark, nonspacing”, and ‘So’ is “Symbol, other”. See the General Category Values section of the Unicode Character Database documentation for a list of category codes.
Unicode Regular Expressions¶
The regular expressions supported by the re module can be provided either as bytes or strings. Some of the special character sequences such as \d and \w have different meanings depending on whether the pattern is supplied as bytes or a string. For example, \d will match the characters [0-9] in bytes but in strings will match any character that’s in the ‘Nd’ category.
The string in this example has the number 57 written in both Thai and Arabic numerals:
When executed, \d+ will match the Thai numerals and print them out. If you supply the re.ASCII flag to compile() , \d+ will match the substring “57” instead.
Similarly, \w matches a wide variety of Unicode characters but only [a-zA-Z0-9_] in bytes or if re.ASCII is supplied, and \s will match either Unicode whitespace characters or [ \t\n\r\f\v] .
References¶
Some good alternative discussions of Python’s Unicode support are:
-
, by Nick Coghlan. , a PyCon 2012 presentation by Ned Batchelder.
The str type is described in the Python library reference at Text Sequence Type — str .
The documentation for the unicodedata module.
The documentation for the codecs module.
Marc-André Lemburg gave a presentation titled “Python and Unicode” (PDF slides) at EuroPython 2002. The slides are an excellent overview of the design of Python 2’s Unicode features (where the Unicode string type is called unicode and literals start with u ).
Reading and Writing Unicode Data¶
Once you’ve written some code that works with Unicode data, the next problem is input/output. How do you get Unicode strings into your program, and how do you convert Unicode into a form suitable for storage or transmission?
It’s possible that you may not need to do anything depending on your input sources and output destinations; you should check whether the libraries used in your application support Unicode natively. XML parsers often return Unicode data, for example. Many relational databases also support Unicode-valued columns and can return Unicode values from an SQL query.
Unicode data is usually converted to a particular encoding before it gets written to disk or sent over a socket. It’s possible to do all the work yourself: open a file, read an 8-bit bytes object from it, and convert the bytes with bytes.decode(encoding) . However, the manual approach is not recommended.
One problem is the multi-byte nature of encodings; one Unicode character can be represented by several bytes. If you want to read the file in arbitrary-sized chunks (say, 1024 or 4096 bytes), you need to write error-handling code to catch the case where only part of the bytes encoding a single Unicode character are read at the end of a chunk. One solution would be to read the entire file into memory and then perform the decoding, but that prevents you from working with files that are extremely large; if you need to read a 2 GiB file, you need 2 GiB of RAM. (More, really, since for at least a moment you’d need to have both the encoded string and its Unicode version in memory.)
The solution would be to use the low-level decoding interface to catch the case of partial coding sequences. The work of implementing this has already been done for you: the built-in open() function can return a file-like object that assumes the file’s contents are in a specified encoding and accepts Unicode parameters for methods such as read() and write() . This works through open() ‘s encoding and errors parameters which are interpreted just like those in str.encode() and bytes.decode() .
Reading Unicode from a file is therefore simple:
It’s also possible to open files in update mode, allowing both reading and writing:
The Unicode character U+FEFF is used as a byte-order mark (BOM), and is often written as the first character of a file in order to assist with autodetection of the file’s byte ordering. Some encodings, such as UTF-16, expect a BOM to be present at the start of a file; when such an encoding is used, the BOM will be automatically written as the first character and will be silently dropped when the file is read. There are variants of these encodings, such as ‘utf-16-le’ and ‘utf-16-be’ for little-endian and big-endian encodings, that specify one particular byte ordering and don’t skip the BOM.
In some areas, it is also convention to use a “BOM” at the start of UTF-8 encoded files; the name is misleading since UTF-8 is not byte-order dependent. The mark simply announces that the file is encoded in UTF-8. Use the ‘utf-8-sig’ codec to automatically skip the mark if present for reading such files.
Unicode filenames¶
Most of the operating systems in common use today support filenames that contain arbitrary Unicode characters. Usually this is implemented by converting the Unicode string into some encoding that varies depending on the system. For example, Mac OS X uses UTF-8 while Windows uses a configurable encoding; on Windows, Python uses the name “mbcs” to refer to whatever the currently configured encoding is. On Unix systems, there will only be a filesystem encoding if you’ve set the LANG or LC_CTYPE environment variables; if you haven’t, the default encoding is UTF-8.
The sys.getfilesystemencoding() function returns the encoding to use on your current system, in case you want to do the encoding manually, but there’s not much reason to bother. When opening a file for reading or writing, you can usually just provide the Unicode string as the filename, and it will be automatically converted to the right encoding for you:
Functions in the os module such as os.stat() will also accept Unicode filenames.
The os.listdir() function returns filenames and raises an issue: should it return the Unicode version of filenames, or should it return bytes containing the encoded versions? os.listdir() will do both, depending on whether you provided the directory path as bytes or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem’s encoding and a list of Unicode strings will be returned, while passing a byte path will return the filenames as bytes. For example, assuming the default filesystem encoding is UTF-8, running the following program:
will produce the following output:
The first list contains UTF-8-encoded filenames, and the second list contains the Unicode versions.
Note that on most occasions, the Unicode APIs should be used. The bytes APIs should only be used on systems where undecodable file names can be present, i.e. Unix systems.
Tips for Writing Unicode-aware Programs¶
This section provides some suggestions on writing software that deals with Unicode.
The most important tip is:
If you attempt to write processing functions that accept both Unicode and byte strings, you will find your program vulnerable to bugs wherever you combine the two different kinds of strings. There is no automatic encoding or decoding: if you do e.g. str + bytes , a TypeError will be raised.
When using data coming from a web browser or some other untrusted source, a common technique is to check for illegal characters in a string before using the string in a generated command line or storing it in a database. If you’re doing this, be careful to check the decoded string, not the encoded bytes data; some encodings may have interesting properties, such as not being bijective or not being fully ASCII-compatible. This is especially true if the input data also specifies the encoding, since the attacker can then choose a clever way to hide malicious text in the encoded bytestream.
Converting Between File Encodings¶
The StreamRecoder class can transparently convert between encodings, taking a stream that returns data in encoding #1 and behaving like a stream returning data in encoding #2.
For example, if you have an input file f that’s in Latin-1, you can wrap it with a StreamRecoder to return bytes encoded in UTF-8:
Files in an Unknown Encoding¶
What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:
The surrogateescape error handler will decode any non-ASCII bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when encoding the data and writing it back out.
References¶
One section of Mastering Python 3 Input/Output, a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling.
The PDF slides for Marc-André Lemburg’s presentation “Writing Unicode-aware Applications in Python” discuss questions of character encodings as well as how to internationalize and localize an application. These slides cover Python 2.x only.
The Guts of Unicode in Python is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode representation in Python 3.3.
Acknowledgements¶
The initial draft of this document was written by Andrew Kuchling. It has since been revised further by Alexander Belopolsky, Georg Brandl, Andrew Kuchling, and Ezio Melotti.
Thanks to the following people who have noted errors or offered suggestions on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Chad Whitacre.