These are the basic Unicode object types used for the Unicode implementation inPython:
Note that UCS2 and UCS4 Python builds are not binary compatible. Please keepthis in mind when writing extensions or interfaces.
The following APIs are really C macros and can be used to do fast checks and toaccess internal read-only data of Unicode objects:
Unicode provides many different character properties. The most often needed onesare available through these macros which are mapped to C functions depending onthe Python configuration.
These APIs can be used for fast direct character conversions:
To create Unicode objects and access their basic sequence properties, use theseAPIs:
Create a Unicode Object from the Py_UNICODE bufferu of the given size.umay beNULL which causes the contents to be undefined. It is the user’sresponsibility to fill in the needed data. The buffer is copied into the newobject. If the buffer is notNULL, the return value might be a shared object.Therefore, modification of the resulting Unicode object is only allowed whenuisNULL.
Take a Cprintf-styleformat string and a variable number ofarguments, calculate the size of the resulting Python unicode string and returna string with the values formatted into it. The variable arguments must be Ctypes and must correspond exactly to the format characters in theformatstring. The following format characters are allowed:
Format Characters | Type | Comment |
---|---|---|
%% | n/a | The literal % character. |
%c | int | A single character,represented as an C int. |
%d | int | Exactly equivalent toprintf("%d"). |
%u | unsigned int | Exactly equivalent toprintf("%u"). |
%ld | long | Exactly equivalent toprintf("%ld"). |
%lu | unsigned long | Exactly equivalent toprintf("%lu"). |
%zd | Py_ssize_t | Exactly equivalent toprintf("%zd"). |
%zu | size_t | Exactly equivalent toprintf("%zu"). |
%i | int | Exactly equivalent toprintf("%i"). |
%x | int | Exactly equivalent toprintf("%x"). |
%s | char* | A null-terminated C characterarray. |
%p | void* | The hex representation of a Cpointer. Mostly equivalent toprintf("%p") except thatit is guaranteed to start withthe literal0x regardlessof what the platform’sprintf yields. |
%A | PyObject* | The result of callingascii(). |
%U | PyObject* | A unicode object. |
%V | PyObject*, char * | A unicode object (which may beNULL) and a null-terminatedC character array as a secondparameter (which will be used,if the first parameter isNULL). |
%S | PyObject* | The result of callingPyObject_Unicode(). |
%R | PyObject* | The result of callingPyObject_Repr(). |
An unrecognized format character causes all the rest of the format string to becopied as-is to the result string, and any extra arguments discarded.
Coerce an encoded objectobj to an Unicode object and return a reference withincremented refcount.
String and other char buffer compatible objects are decoded according to thegiven encoding and using the error handling defined by errors. Both can beNULL to have the interface use the default values (see the next section fordetails).
All other objects, including Unicode objects, cause aTypeError to beset.
The API returnsNULL if there was an error. The caller is responsible fordecref’ing the returned objects.
Shortcut forPyUnicode_FromEncodedObject(obj,NULL,"strict") which is usedthroughout the interpreter whenever coercion to Unicode is needed.
If the platform supportswchar_t and provides a header file wchar.h,Python can interface directly to this type using the following functions.Support is optimized if Python’s ownPy_UNICODE type is identical tothe system’swchar_t.
Create a Unicode object from thewchar_t bufferw of the given size.Passing -1 as the size indicates that the function must itself compute the length,using wcslen.ReturnNULL on failure.
Python provides a set of builtin codecs which are written in C for speed. All ofthese codecs are directly usable via the following functions.
Many of the following APIs take two arguments encoding and errors. Theseparameters encoding and errors have the same semantics as the ones of thebuiltin unicode() Unicode object constructor.
Setting encoding toNULL causes the default encoding to be used which isASCII. The file system calls should usePy_FileSystemDefaultEncodingas the encoding for file names. This variable should be treated as read-only: Onsome systems, it will be a pointer to a static string, on others, it will changeat run-time (such as when the application invokes setlocale).
Error handling is set by errors which may also be set toNULL meaning to usethe default handling defined for the codec. Default error handling for allbuiltin codecs is “strict” (ValueError is raised).
The codecs all use a similar interface. Only deviation from the followinggeneric ones are documented for simplicity.
These are the generic codec APIs:
Create a Unicode object by decodingsize bytes of the encoded strings.encoding anderrors have the same meaning as the parameters of the same namein theunicode() builtin function. The codec to be used is looked upusing the Python codec registry. ReturnNULL if an exception was raised bythe codec.
Encode thePy_UNICODE buffer of the given size and return a Pythonstring object.encoding anderrors have the same meaning as the parametersof the same name in the Unicodeencode() method. The codec to be used islooked up using the Python codec registry. ReturnNULL if an exception wasraised by the codec.
Encode a Unicode object and return the result as Python string object.encoding anderrors have the same meaning as the parameters of the same namein the Unicodeencode() method. The codec to be used is looked up usingthe Python codec registry. ReturnNULL if an exception was raised by thecodec.
These are the UTF-8 codec APIs:
Create a Unicode object by decodingsize bytes of the UTF-8 encoded strings. ReturnNULL if an exception was raised by the codec.
Ifconsumed isNULL, behave likePyUnicode_DecodeUTF8. Ifconsumed is notNULL, trailing incomplete UTF-8 byte sequences will not betreated as an error. Those bytes will not be decoded and the number of bytesthat have been decoded will be stored inconsumed.
Encode thePy_UNICODE buffer of the given size using UTF-8 and return aPython string object. ReturnNULL if an exception was raised by the codec.
Encode a Unicode object using UTF-8 and return the result as Python stringobject. Error handling is “strict”. ReturnNULL if an exception was raisedby the codec.
These are the UTF-32 codec APIs:
Decodelength bytes from a UTF-32 encoded buffer string and return thecorresponding Unicode object.errors (if non-NULL) defines the errorhandling. It defaults to “strict”.
Ifbyteorder is non-NULL, the decoder starts decoding using the given byteorder:
*byteorder==-1:littleendian*byteorder==0:nativeorder*byteorder==1:bigendian
and then switches if the first four bytes of the input data are a byte order mark(BOM) and the specified byte order is native order. This BOM is not copied intothe resulting Unicode string. After completion,*byteorder is set to thecurrent byte order at the end of input data.
In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
Ifbyteorder isNULL, the codec starts in native order mode.
ReturnNULL if an exception was raised by the codec.
Return a Python bytes object holding the UTF-32 encoded value of the Unicodedata ins. Ifbyteorder is not0, output is written according to thefollowing byte order:
byteorder==-1:littleendianbyteorder==0:nativebyteorder(writesaBOMmark)byteorder==1:bigendian
If byteorder is0, the output string will always start with the Unicode BOMmark (U+FEFF). In the other two modes, no BOM mark is prepended.
IfPy_UNICODE_WIDE is not defined, surrogate pairs will be outputas a single codepoint.
ReturnNULL if an exception was raised by the codec.
These are the UTF-16 codec APIs:
Decodelength bytes from a UTF-16 encoded buffer string and return thecorresponding Unicode object.errors (if non-NULL) defines the errorhandling. It defaults to “strict”.
Ifbyteorder is non-NULL, the decoder starts decoding using the given byteorder:
*byteorder==-1:littleendian*byteorder==0:nativeorder*byteorder==1:bigendian
and then switches if the first two bytes of the input data are a byte order mark(BOM) and the specified byte order is native order. This BOM is not copied intothe resulting Unicode string. After completion,*byteorder is set to thecurrent byte order at the end of input data.
Ifbyteorder isNULL, the codec starts in native order mode.
ReturnNULL if an exception was raised by the codec.
Ifconsumed isNULL, behave likePyUnicode_DecodeUTF16. Ifconsumed is notNULL,PyUnicode_DecodeUTF16Stateful will not treattrailing incomplete UTF-16 byte sequences (such as an odd number of bytes or asplit surrogate pair) as an error. Those bytes will not be decoded and thenumber of bytes that have been decoded will be stored inconsumed.
Return a Python string object holding the UTF-16 encoded value of the Unicodedata ins. Ifbyteorder is not0, output is written according to thefollowing byte order:
byteorder==-1:littleendianbyteorder==0:nativebyteorder(writesaBOMmark)byteorder==1:bigendian
If byteorder is0, the output string will always start with the Unicode BOMmark (U+FEFF). In the other two modes, no BOM mark is prepended.
IfPy_UNICODE_WIDE is defined, a singlePy_UNICODE value may getrepresented as a surrogate pair. If it is not defined, eachPy_UNICODEvalues is interpreted as an UCS-2 character.
ReturnNULL if an exception was raised by the codec.
Return a Python string using the UTF-16 encoding in native byte order. Thestring always starts with a BOM mark. Error handling is “strict”. ReturnNULL if an exception was raised by the codec.
These are the “Unicode Escape” codec APIs:
Create a Unicode object by decodingsize bytes of the Unicode-Escape encodedstrings. ReturnNULL if an exception was raised by the codec.
Encode thePy_UNICODE buffer of the given size using Unicode-Escape andreturn a Python string object. ReturnNULL if an exception was raised by thecodec.
Encode a Unicode object using Unicode-Escape and return the result as Pythonstring object. Error handling is “strict”. ReturnNULL if an exception wasraised by the codec.
These are the “Raw Unicode Escape” codec APIs:
Create a Unicode object by decodingsize bytes of the Raw-Unicode-Escapeencoded strings. ReturnNULL if an exception was raised by the codec.
Encode thePy_UNICODE buffer of the given size using Raw-Unicode-Escapeand return a Python string object. ReturnNULL if an exception was raised bythe codec.
Encode a Unicode object using Raw-Unicode-Escape and return the result asPython string object. Error handling is “strict”. ReturnNULL if an exceptionwas raised by the codec.
These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicodeordinals and only these are accepted by the codecs during encoding.
Create a Unicode object by decodingsize bytes of the Latin-1 encoded strings. ReturnNULL if an exception was raised by the codec.
Encode thePy_UNICODE buffer of the given size using Latin-1 and returna Python string object. ReturnNULL if an exception was raised by the codec.
Encode a Unicode object using Latin-1 and return the result as Python stringobject. Error handling is “strict”. ReturnNULL if an exception was raisedby the codec.
These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All othercodes generate errors.
Create a Unicode object by decodingsize bytes of the ASCII encoded strings. ReturnNULL if an exception was raised by the codec.
Encode thePy_UNICODE buffer of the given size using ASCII and return aPython string object. ReturnNULL if an exception was raised by the codec.
Encode a Unicode object using ASCII and return the result as Python stringobject. Error handling is “strict”. ReturnNULL if an exception was raisedby the codec.
These are the mapping codec APIs:
This codec is special in that it can be used to implement many different codecs(and this is in fact what was done to obtain most of the standard codecsincluded in theencodings package). The codec uses mapping to encode anddecode characters.
Decoding mappings must map single string characters to single Unicodecharacters, integers (which are then interpreted as Unicode ordinals) or None(meaning “undefined mapping” and causing an error).
Encoding mappings must map single Unicode characters to single stringcharacters, integers (which are then interpreted as Latin-1 ordinals) or None(meaning “undefined mapping” and causing an error).
The mapping objects provided must only support the __getitem__ mappinginterface.
If a character lookup fails with a LookupError, the character is copied as-ismeaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinalresp. Because of this, mappings only need to contain those mappings which mapcharacters to different code points.
Create a Unicode object by decodingsize bytes of the encoded strings usingthe givenmapping object. ReturnNULL if an exception was raised by thecodec. Ifmapping isNULL latin-1 decoding will be done. Else it can be adictionary mapping byte or a unicode string, which is treated as a lookup table.Byte values greater that the length of the string and U+FFFE “characters” aretreated as “undefined mapping”.
Encode thePy_UNICODE buffer of the given size using the givenmapping object and return a Python string object. ReturnNULL if anexception was raised by the codec.
Encode a Unicode object using the givenmapping object and return the resultas Python string object. Error handling is “strict”. ReturnNULL if anexception was raised by the codec.
The following codec API is special in that maps Unicode to Unicode.
Translate aPy_UNICODE buffer of the given length by applying acharacter mappingtable to it and return the resulting Unicode object. ReturnNULL when an exception was raised by the codec.
Themapping table must map Unicode ordinal integers to Unicode ordinalintegers or None (causing deletion of the character).
Mapping tables need only provide the__getitem__() interface; dictionariesand sequences work well. Unmapped character ordinals (ones which cause aLookupError) are left untouched and are copied as-is.
These are the MBCS codec APIs. They are currently only available on Windows anduse the Win32 MBCS converters to implement the conversions. Note that MBCS (orDBCS) is a class of encodings, not just one. The target encoding is defined bythe user settings on the machine running the codec.
Create a Unicode object by decodingsize bytes of the MBCS encoded strings.ReturnNULL if an exception was raised by the codec.
Encode thePy_UNICODE buffer of the given size using MBCS and return aPython string object. ReturnNULL if an exception was raised by the codec.
The following APIs are capable of handling Unicode objects and strings on input(we refer to them as strings in the descriptions) and return Unicode objects orintegers as appropriate.
They all returnNULL or-1 if an exception occurs.
Concat two strings giving a new Unicode string.
Split a string giving a list of Unicode strings. If sep isNULL, splittingwill be done at all whitespace substrings. Otherwise, splits occur at the givenseparator. At mostmaxsplit splits will be done. If negative, no limit isset. Separators are not included in the resulting list.
Split a Unicode string at line breaks, returning a list of Unicode strings.CRLF is considered to be one line break. Ifkeepend is 0, the Line breakcharacters are not included in the resulting strings.
Translate a string by applying a character mapping table to it and return theresulting Unicode object.
The mapping table must map Unicode ordinal integers to Unicode ordinal integersor None (causing deletion of the character).
Mapping tables need only provide the__getitem__() interface; dictionariesand sequences work well. Unmapped character ordinals (ones which cause aLookupError) are left untouched and are copied as-is.
errors has the usual meaning for codecs. It may beNULL which indicates touse the default error handling.
Join a sequence of strings using the given separator and return the resultingUnicode string.
Return 1 ifsubstr matchesstr*[*start:end] at the given tail end(direction == -1 means to do a prefix match,direction == 1 a suffix match),0 otherwise. Return-1 if an error occurred.
Replace at mostmaxcount occurrences ofsubstr instr withreplstr andreturn the resulting Unicode object.maxcount == -1 means replace alloccurrences.
Rich compare two unicode strings and return one of the following:
Note thatPy_EQ andPy_NE comparisons can cause aUnicodeWarning in case the conversion of the arguments to Unicode failswith aUnicodeDecodeError.
Possible values forop arePy_GT,Py_GE,Py_EQ,Py_NE,Py_LT, andPy_LE.
Return a new string object fromformat andargs; this is analogous toformat%args. Theargs argument must be a tuple.
Check whetherelement is contained incontainer and return true or falseaccordingly.
element has to coerce to a one element Unicode string.-1 is returned ifthere was an error.
Enter search terms or a module, class or function name.