blob: 0455ae58968394f58dd345f880e78658a8a60f44 [file] [log] [blame]
Georg Brandl54a3faa2008-01-20 09:30:57 +00001.. highlightlang:: c
2
3.. _unicodeobjects:
4
5Unicode Objects and Codecs
6--------------------------
7
8.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
9
10Unicode Objects
11^^^^^^^^^^^^^^^
12
13These are the basic Unicode object types used for the Unicode implementation in
14Python:
15
16.. % --- Unicode Type -------------------------------------------------------
17
18
19.. ctype:: Py_UNICODE
20
21 This type represents the storage type which is used by Python internally as
22 basis for holding Unicode ordinals. Python's default builds use a 16-bit type
23 for :ctype:`Py_UNICODE` and store Unicode values internally as UCS2. It is also
24 possible to build a UCS4 version of Python (most recent Linux distributions come
25 with UCS4 builds of Python). These builds then use a 32-bit type for
26 :ctype:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms
27 where :ctype:`wchar_t` is available and compatible with the chosen Python
28 Unicode build variant, :ctype:`Py_UNICODE` is a typedef alias for
29 :ctype:`wchar_t` to enhance native platform compatibility. On all other
30 platforms, :ctype:`Py_UNICODE` is a typedef alias for either :ctype:`unsigned
31 short` (UCS2) or :ctype:`unsigned long` (UCS4).
32
33Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep
34this in mind when writing extensions or interfaces.
35
36
37.. ctype:: PyUnicodeObject
38
39 This subtype of :ctype:`PyObject` represents a Python Unicode object.
40
41
42.. cvar:: PyTypeObject PyUnicode_Type
43
44 This instance of :ctype:`PyTypeObject` represents the Python Unicode type. It
45 is exposed to Python code as ``str``.
46
47The following APIs are really C macros and can be used to do fast checks and to
48access internal read-only data of Unicode objects:
49
50
51.. cfunction:: int PyUnicode_Check(PyObject *o)
52
53 Return true if the object *o* is a Unicode object or an instance of a Unicode
54 subtype.
55
56
57.. cfunction:: int PyUnicode_CheckExact(PyObject *o)
58
59 Return true if the object *o* is a Unicode object, but not an instance of a
60 subtype.
61
62
63.. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)
64
65 Return the size of the object. *o* has to be a :ctype:`PyUnicodeObject` (not
66 checked).
67
68
69.. cfunction:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)
70
71 Return the size of the object's internal buffer in bytes. *o* has to be a
72 :ctype:`PyUnicodeObject` (not checked).
73
74
75.. cfunction:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)
76
77 Return a pointer to the internal :ctype:`Py_UNICODE` buffer of the object. *o*
78 has to be a :ctype:`PyUnicodeObject` (not checked).
79
80
81.. cfunction:: const char* PyUnicode_AS_DATA(PyObject *o)
82
83 Return a pointer to the internal buffer of the object. *o* has to be a
84 :ctype:`PyUnicodeObject` (not checked).
85
Christian Heimesa156e092008-02-16 07:38:31 +000086
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +000087.. cfunction:: int PyUnicode_ClearFreeList()
Christian Heimesa156e092008-02-16 07:38:31 +000088
89 Clear the free list. Return the total number of freed items.
90
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +000091
Georg Brandl54a3faa2008-01-20 09:30:57 +000092Unicode provides many different character properties. The most often needed ones
93are available through these macros which are mapped to C functions depending on
94the Python configuration.
95
96.. % --- Unicode character properties ---------------------------------------
97
98
99.. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch)
100
101 Return 1 or 0 depending on whether *ch* is a whitespace character.
102
103
104.. cfunction:: int Py_UNICODE_ISLOWER(Py_UNICODE ch)
105
106 Return 1 or 0 depending on whether *ch* is a lowercase character.
107
108
109.. cfunction:: int Py_UNICODE_ISUPPER(Py_UNICODE ch)
110
111 Return 1 or 0 depending on whether *ch* is an uppercase character.
112
113
114.. cfunction:: int Py_UNICODE_ISTITLE(Py_UNICODE ch)
115
116 Return 1 or 0 depending on whether *ch* is a titlecase character.
117
118
119.. cfunction:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)
120
121 Return 1 or 0 depending on whether *ch* is a linebreak character.
122
123
124.. cfunction:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)
125
126 Return 1 or 0 depending on whether *ch* is a decimal character.
127
128
129.. cfunction:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch)
130
131 Return 1 or 0 depending on whether *ch* is a digit character.
132
133
134.. cfunction:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)
135
136 Return 1 or 0 depending on whether *ch* is a numeric character.
137
138
139.. cfunction:: int Py_UNICODE_ISALPHA(Py_UNICODE ch)
140
141 Return 1 or 0 depending on whether *ch* is an alphabetic character.
142
143
144.. cfunction:: int Py_UNICODE_ISALNUM(Py_UNICODE ch)
145
146 Return 1 or 0 depending on whether *ch* is an alphanumeric character.
147
Georg Brandl559e5d72008-06-11 18:37:52 +0000148
149.. cfunction:: int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch)
150
151 Return 1 or 0 depending on whether *ch* is a printable character.
152 Nonprintable characters are those characters defined in the Unicode character
153 database as "Other" or "Separator", excepting the ASCII space (0x20) which is
154 considered printable. (Note that printable characters in this context are
155 those which should not be escaped when :func:`repr` is invoked on a string.
156 It has no bearing on the handling of strings written to :data:`sys.stdout` or
157 :data:`sys.stderr`.)
158
159
Georg Brandl54a3faa2008-01-20 09:30:57 +0000160These APIs can be used for fast direct character conversions:
161
162
163.. cfunction:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch)
164
165 Return the character *ch* converted to lower case.
166
167
168.. cfunction:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch)
169
170 Return the character *ch* converted to upper case.
171
172
173.. cfunction:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch)
174
175 Return the character *ch* converted to title case.
176
177
178.. cfunction:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch)
179
180 Return the character *ch* converted to a decimal positive integer. Return
181 ``-1`` if this is not possible. This macro does not raise exceptions.
182
183
184.. cfunction:: int Py_UNICODE_TODIGIT(Py_UNICODE ch)
185
186 Return the character *ch* converted to a single digit integer. Return ``-1`` if
187 this is not possible. This macro does not raise exceptions.
188
189
190.. cfunction:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch)
191
192 Return the character *ch* converted to a double. Return ``-1.0`` if this is not
193 possible. This macro does not raise exceptions.
194
195To create Unicode objects and access their basic sequence properties, use these
196APIs:
197
198.. % --- Plain Py_UNICODE ---------------------------------------------------
199
200
201.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
202
203 Create a Unicode Object from the Py_UNICODE buffer *u* of the given size. *u*
204 may be *NULL* which causes the contents to be undefined. It is the user's
205 responsibility to fill in the needed data. The buffer is copied into the new
206 object. If the buffer is not *NULL*, the return value might be a shared object.
207 Therefore, modification of the resulting Unicode object is only allowed when *u*
208 is *NULL*.
209
210
211.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
212
213 Create a Unicode Object from the char buffer *u*. The bytes will be interpreted
214 as being UTF-8 encoded. *u* may also be *NULL* which
215 causes the contents to be undefined. It is the user's responsibility to fill in
216 the needed data. The buffer is copied into the new object. If the buffer is not
217 *NULL*, the return value might be a shared object. Therefore, modification of
218 the resulting Unicode object is only allowed when *u* is *NULL*.
219
220
221.. cfunction:: PyObject *PyUnicode_FromString(const char *u)
222
223 Create a Unicode object from an UTF-8 encoded null-terminated char buffer
224 *u*.
225
226
227.. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...)
228
229 Take a C :cfunc:`printf`\ -style *format* string and a variable number of
230 arguments, calculate the size of the resulting Python unicode string and return
231 a string with the values formatted into it. The variable arguments must be C
232 types and must correspond exactly to the format characters in the *format*
233 string. The following format characters are allowed:
234
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000235 .. % This should be exactly the same as the table in PyErr_Format.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000236 .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
237 .. % because not all compilers support the %z width modifier -- we fake it
238 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000239 .. % Similar comments apply to the %ll width modifier and
240 .. % PY_FORMAT_LONG_LONG.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000241
242 +-------------------+---------------------+--------------------------------+
243 | Format Characters | Type | Comment |
244 +===================+=====================+================================+
245 | :attr:`%%` | *n/a* | The literal % character. |
246 +-------------------+---------------------+--------------------------------+
247 | :attr:`%c` | int | A single character, |
248 | | | represented as an C int. |
249 +-------------------+---------------------+--------------------------------+
250 | :attr:`%d` | int | Exactly equivalent to |
251 | | | ``printf("%d")``. |
252 +-------------------+---------------------+--------------------------------+
253 | :attr:`%u` | unsigned int | Exactly equivalent to |
254 | | | ``printf("%u")``. |
255 +-------------------+---------------------+--------------------------------+
256 | :attr:`%ld` | long | Exactly equivalent to |
257 | | | ``printf("%ld")``. |
258 +-------------------+---------------------+--------------------------------+
259 | :attr:`%lu` | unsigned long | Exactly equivalent to |
260 | | | ``printf("%lu")``. |
261 +-------------------+---------------------+--------------------------------+
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000262 | :attr:`%lld` | long long | Exactly equivalent to |
263 | | | ``printf("%lld")``. |
264 +-------------------+---------------------+--------------------------------+
265 | :attr:`%llu` | unsigned long long | Exactly equivalent to |
266 | | | ``printf("%llu")``. |
267 +-------------------+---------------------+--------------------------------+
Georg Brandl54a3faa2008-01-20 09:30:57 +0000268 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
269 | | | ``printf("%zd")``. |
270 +-------------------+---------------------+--------------------------------+
271 | :attr:`%zu` | size_t | Exactly equivalent to |
272 | | | ``printf("%zu")``. |
273 +-------------------+---------------------+--------------------------------+
274 | :attr:`%i` | int | Exactly equivalent to |
275 | | | ``printf("%i")``. |
276 +-------------------+---------------------+--------------------------------+
277 | :attr:`%x` | int | Exactly equivalent to |
278 | | | ``printf("%x")``. |
279 +-------------------+---------------------+--------------------------------+
280 | :attr:`%s` | char\* | A null-terminated C character |
281 | | | array. |
282 +-------------------+---------------------+--------------------------------+
283 | :attr:`%p` | void\* | The hex representation of a C |
284 | | | pointer. Mostly equivalent to |
285 | | | ``printf("%p")`` except that |
286 | | | it is guaranteed to start with |
287 | | | the literal ``0x`` regardless |
288 | | | of what the platform's |
289 | | | ``printf`` yields. |
290 +-------------------+---------------------+--------------------------------+
Georg Brandl559e5d72008-06-11 18:37:52 +0000291 | :attr:`%A` | PyObject\* | The result of calling |
292 | | | :func:`ascii`. |
293 +-------------------+---------------------+--------------------------------+
Georg Brandl54a3faa2008-01-20 09:30:57 +0000294 | :attr:`%U` | PyObject\* | A unicode object. |
295 +-------------------+---------------------+--------------------------------+
296 | :attr:`%V` | PyObject\*, char \* | A unicode object (which may be |
297 | | | *NULL*) and a null-terminated |
298 | | | C character array as a second |
299 | | | parameter (which will be used, |
300 | | | if the first parameter is |
301 | | | *NULL*). |
302 +-------------------+---------------------+--------------------------------+
303 | :attr:`%S` | PyObject\* | The result of calling |
Benjamin Petersone8662062009-03-08 23:51:13 +0000304 | | | :func:`PyObject_Str`. |
Georg Brandl54a3faa2008-01-20 09:30:57 +0000305 +-------------------+---------------------+--------------------------------+
306 | :attr:`%R` | PyObject\* | The result of calling |
307 | | | :func:`PyObject_Repr`. |
308 +-------------------+---------------------+--------------------------------+
309
310 An unrecognized format character causes all the rest of the format string to be
311 copied as-is to the result string, and any extra arguments discarded.
312
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000313 .. note::
314
315 The `"%lld"` and `"%llu"` format specifiers are only available
316 when `HAVE_LONG_LONG` is defined.
317
318 .. versionchanged:: 3.2
319 Support for `"%lld"` and `"%llu"` added.
320
321
Georg Brandl54a3faa2008-01-20 09:30:57 +0000322
323.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
324
325 Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
326 arguments.
327
328
329.. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)
330
331 Return a read-only pointer to the Unicode object's internal :ctype:`Py_UNICODE`
332 buffer, *NULL* if *unicode* is not a Unicode object.
333
334
335.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
336
337 Return the length of the Unicode object.
338
339
340.. cfunction:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
341
342 Coerce an encoded object *obj* to an Unicode object and return a reference with
343 incremented refcount.
344
345 String and other char buffer compatible objects are decoded according to the
346 given encoding and using the error handling defined by errors. Both can be
347 *NULL* to have the interface use the default values (see the next section for
348 details).
349
350 All other objects, including Unicode objects, cause a :exc:`TypeError` to be
351 set.
352
353 The API returns *NULL* if there was an error. The caller is responsible for
354 decref'ing the returned objects.
355
356
357.. cfunction:: PyObject* PyUnicode_FromObject(PyObject *obj)
358
359 Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used
360 throughout the interpreter whenever coercion to Unicode is needed.
361
362If the platform supports :ctype:`wchar_t` and provides a header file wchar.h,
363Python can interface directly to this type using the following functions.
364Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to
365the system's :ctype:`wchar_t`.
366
367.. % --- wchar_t support for platforms which support it ---------------------
368
369
370.. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
371
372 Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size.
Martin v. Löwis790465f2008-04-05 20:41:37 +0000373 Passing -1 as the size indicates that the function must itself compute the length,
374 using wcslen.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000375 Return *NULL* on failure.
376
377
378.. cfunction:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size)
379
380 Copy the Unicode object contents into the :ctype:`wchar_t` buffer *w*. At most
381 *size* :ctype:`wchar_t` characters are copied (excluding a possibly trailing
382 0-termination character). Return the number of :ctype:`wchar_t` characters
383 copied or -1 in case of an error. Note that the resulting :ctype:`wchar_t`
384 string may or may not be 0-terminated. It is the responsibility of the caller
385 to make sure that the :ctype:`wchar_t` string is 0-terminated in case this is
386 required by the application.
387
388
389.. _builtincodecs:
390
391Built-in Codecs
392^^^^^^^^^^^^^^^
393
Georg Brandl22b34312009-07-26 14:54:51 +0000394Python provides a set of built-in codecs which are written in C for speed. All of
Georg Brandl54a3faa2008-01-20 09:30:57 +0000395these codecs are directly usable via the following functions.
396
397Many of the following APIs take two arguments encoding and errors. These
398parameters encoding and errors have the same semantics as the ones of the
Georg Brandl22b34312009-07-26 14:54:51 +0000399built-in :func:`unicode` Unicode object constructor.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000400
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000401Setting encoding to *NULL* causes the default encoding to be used
402which is ASCII. The file system calls should use
403:cfunc:`PyUnicode_FSConverter` for encoding file names. This uses the
404variable :cdata:`Py_FileSystemDefaultEncoding` internally. This
405variable should be treated as read-only: On some systems, it will be a
406pointer to a static string, on others, it will change at run-time
407(such as when the application invokes setlocale).
Georg Brandl54a3faa2008-01-20 09:30:57 +0000408
409Error handling is set by errors which may also be set to *NULL* meaning to use
410the default handling defined for the codec. Default error handling for all
Georg Brandl22b34312009-07-26 14:54:51 +0000411built-in codecs is "strict" (:exc:`ValueError` is raised).
Georg Brandl54a3faa2008-01-20 09:30:57 +0000412
413The codecs all use a similar interface. Only deviation from the following
414generic ones are documented for simplicity.
415
416These are the generic codec APIs:
417
418.. % --- Generic Codecs -----------------------------------------------------
419
420
421.. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
422
423 Create a Unicode object by decoding *size* bytes of the encoded string *s*.
424 *encoding* and *errors* have the same meaning as the parameters of the same name
Georg Brandl22b34312009-07-26 14:54:51 +0000425 in the :func:`unicode` built-in function. The codec to be used is looked up
Georg Brandl54a3faa2008-01-20 09:30:57 +0000426 using the Python codec registry. Return *NULL* if an exception was raised by
427 the codec.
428
429
430.. cfunction:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)
431
432 Encode the :ctype:`Py_UNICODE` buffer of the given size and return a Python
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000433 bytes object. *encoding* and *errors* have the same meaning as the
434 parameters of the same name in the Unicode :meth:`encode` method. The codec
435 to be used is looked up using the Python codec registry. Return *NULL* if an
436 exception was raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000437
438
439.. cfunction:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
440
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000441 Encode a Unicode object and return the result as Python bytes object.
442 *encoding* and *errors* have the same meaning as the parameters of the same
443 name in the Unicode :meth:`encode` method. The codec to be used is looked up
444 using the Python codec registry. Return *NULL* if an exception was raised by
445 the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000446
447These are the UTF-8 codec APIs:
448
449.. % --- UTF-8 Codecs -------------------------------------------------------
450
451
452.. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)
453
454 Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
455 *s*. Return *NULL* if an exception was raised by the codec.
456
457
458.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
459
460 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF8`. If
461 *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be
462 treated as an error. Those bytes will not be decoded and the number of bytes
463 that have been decoded will be stored in *consumed*.
464
465
466.. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
467
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000468 Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-8 and
469 return a Python bytes object. Return *NULL* if an exception was raised by
470 the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000471
472
473.. cfunction:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode)
474
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000475 Encode a Unicode object using UTF-8 and return the result as Python bytes
476 object. Error handling is "strict". Return *NULL* if an exception was
477 raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000478
479These are the UTF-32 codec APIs:
480
481.. % --- UTF-32 Codecs ------------------------------------------------------ */
482
483
484.. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
485
486 Decode *length* bytes from a UTF-32 encoded buffer string and return the
487 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
488 handling. It defaults to "strict".
489
490 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
491 order::
492
493 *byteorder == -1: little endian
494 *byteorder == 0: native order
495 *byteorder == 1: big endian
496
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000497 If ``*byteorder`` is zero, and the first four bytes of the input data are a
498 byte order mark (BOM), the decoder switches to this byte order and the BOM is
499 not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or
500 ``1``, any byte order mark is copied to the output.
501
502 After completion, *\*byteorder* is set to the current byte order at the end
503 of input data.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000504
505 In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
506
507 If *byteorder* is *NULL*, the codec starts in native order mode.
508
509 Return *NULL* if an exception was raised by the codec.
510
511
512.. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
513
514 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF32`. If
515 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF32Stateful` will not treat
516 trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
517 by four) as an error. Those bytes will not be decoded and the number of bytes
518 that have been decoded will be stored in *consumed*.
519
520
521.. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
522
523 Return a Python bytes object holding the UTF-32 encoded value of the Unicode
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000524 data in *s*. Output is written according to the following byte order::
Georg Brandl54a3faa2008-01-20 09:30:57 +0000525
526 byteorder == -1: little endian
527 byteorder == 0: native byte order (writes a BOM mark)
528 byteorder == 1: big endian
529
530 If byteorder is ``0``, the output string will always start with the Unicode BOM
531 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
532
533 If *Py_UNICODE_WIDE* is not defined, surrogate pairs will be output
534 as a single codepoint.
535
536 Return *NULL* if an exception was raised by the codec.
537
538
539.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
540
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000541 Return a Python byte string using the UTF-32 encoding in native byte
542 order. The string always starts with a BOM mark. Error handling is "strict".
543 Return *NULL* if an exception was raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000544
545
546These are the UTF-16 codec APIs:
547
548.. % --- UTF-16 Codecs ------------------------------------------------------ */
549
550
551.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
552
553 Decode *length* bytes from a UTF-16 encoded buffer string and return the
554 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
555 handling. It defaults to "strict".
556
557 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
558 order::
559
560 *byteorder == -1: little endian
561 *byteorder == 0: native order
562 *byteorder == 1: big endian
563
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000564 If ``*byteorder`` is zero, and the first two bytes of the input data are a
565 byte order mark (BOM), the decoder switches to this byte order and the BOM is
566 not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or
567 ``1``, any byte order mark is copied to the output (where it will result in
568 either a ``\ufeff`` or a ``\ufffe`` character).
569
570 After completion, *\*byteorder* is set to the current byte order at the end
571 of input data.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000572
573 If *byteorder* is *NULL*, the codec starts in native order mode.
574
575 Return *NULL* if an exception was raised by the codec.
576
577
578.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
579
580 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If
581 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat
582 trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
583 split surrogate pair) as an error. Those bytes will not be decoded and the
584 number of bytes that have been decoded will be stored in *consumed*.
585
586
587.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
588
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000589 Return a Python bytes object holding the UTF-16 encoded value of the Unicode
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000590 data in *s*. Output is written according to the following byte order::
Georg Brandl54a3faa2008-01-20 09:30:57 +0000591
592 byteorder == -1: little endian
593 byteorder == 0: native byte order (writes a BOM mark)
594 byteorder == 1: big endian
595
596 If byteorder is ``0``, the output string will always start with the Unicode BOM
597 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
598
599 If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get
600 represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE`
601 values is interpreted as an UCS-2 character.
602
603 Return *NULL* if an exception was raised by the codec.
604
605
606.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
607
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000608 Return a Python byte string using the UTF-16 encoding in native byte
609 order. The string always starts with a BOM mark. Error handling is "strict".
610 Return *NULL* if an exception was raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000611
612These are the "Unicode Escape" codec APIs:
613
614.. % --- Unicode-Escape Codecs ----------------------------------------------
615
616
617.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
618
619 Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
620 string *s*. Return *NULL* if an exception was raised by the codec.
621
622
623.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
624
625 Encode the :ctype:`Py_UNICODE` buffer of the given size using Unicode-Escape and
626 return a Python string object. Return *NULL* if an exception was raised by the
627 codec.
628
629
630.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
631
632 Encode a Unicode object using Unicode-Escape and return the result as Python
633 string object. Error handling is "strict". Return *NULL* if an exception was
634 raised by the codec.
635
636These are the "Raw Unicode Escape" codec APIs:
637
638.. % --- Raw-Unicode-Escape Codecs ------------------------------------------
639
640
641.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
642
643 Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
644 encoded string *s*. Return *NULL* if an exception was raised by the codec.
645
646
647.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
648
649 Encode the :ctype:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape
650 and return a Python string object. Return *NULL* if an exception was raised by
651 the codec.
652
653
654.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
655
656 Encode a Unicode object using Raw-Unicode-Escape and return the result as
657 Python string object. Error handling is "strict". Return *NULL* if an exception
658 was raised by the codec.
659
660These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
661ordinals and only these are accepted by the codecs during encoding.
662
663.. % --- Latin-1 Codecs -----------------------------------------------------
664
665
666.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)
667
668 Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
669 *s*. Return *NULL* if an exception was raised by the codec.
670
671
672.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
673
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000674 Encode the :ctype:`Py_UNICODE` buffer of the given size using Latin-1 and
675 return a Python bytes object. Return *NULL* if an exception was raised by
676 the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000677
678
679.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
680
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000681 Encode a Unicode object using Latin-1 and return the result as Python bytes
682 object. Error handling is "strict". Return *NULL* if an exception was
683 raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000684
685These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
686codes generate errors.
687
688.. % --- ASCII Codecs -------------------------------------------------------
689
690
691.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
692
693 Create a Unicode object by decoding *size* bytes of the ASCII encoded string
694 *s*. Return *NULL* if an exception was raised by the codec.
695
696
697.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
698
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000699 Encode the :ctype:`Py_UNICODE` buffer of the given size using ASCII and
700 return a Python bytes object. Return *NULL* if an exception was raised by
701 the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000702
703
704.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
705
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000706 Encode a Unicode object using ASCII and return the result as Python bytes
707 object. Error handling is "strict". Return *NULL* if an exception was
708 raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000709
710These are the mapping codec APIs:
711
712.. % --- Character Map Codecs -----------------------------------------------
713
714This codec is special in that it can be used to implement many different codecs
715(and this is in fact what was done to obtain most of the standard codecs
716included in the :mod:`encodings` package). The codec uses mapping to encode and
717decode characters.
718
719Decoding mappings must map single string characters to single Unicode
720characters, integers (which are then interpreted as Unicode ordinals) or None
721(meaning "undefined mapping" and causing an error).
722
723Encoding mappings must map single Unicode characters to single string
724characters, integers (which are then interpreted as Latin-1 ordinals) or None
725(meaning "undefined mapping" and causing an error).
726
727The mapping objects provided must only support the __getitem__ mapping
728interface.
729
730If a character lookup fails with a LookupError, the character is copied as-is
731meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
732resp. Because of this, mappings only need to contain those mappings which map
733characters to different code points.
734
735
736.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors)
737
738 Create a Unicode object by decoding *size* bytes of the encoded string *s* using
739 the given *mapping* object. Return *NULL* if an exception was raised by the
740 codec. If *mapping* is *NULL* latin-1 decoding will be done. Else it can be a
741 dictionary mapping byte or a unicode string, which is treated as a lookup table.
742 Byte values greater that the length of the string and U+FFFE "characters" are
743 treated as "undefined mapping".
744
745
746.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
747
748 Encode the :ctype:`Py_UNICODE` buffer of the given size using the given
749 *mapping* object and return a Python string object. Return *NULL* if an
750 exception was raised by the codec.
751
752
753.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
754
755 Encode a Unicode object using the given *mapping* object and return the result
756 as Python string object. Error handling is "strict". Return *NULL* if an
757 exception was raised by the codec.
758
759The following codec API is special in that maps Unicode to Unicode.
760
761
762.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors)
763
764 Translate a :ctype:`Py_UNICODE` buffer of the given length by applying a
765 character mapping *table* to it and return the resulting Unicode object. Return
766 *NULL* when an exception was raised by the codec.
767
768 The *mapping* table must map Unicode ordinal integers to Unicode ordinal
769 integers or None (causing deletion of the character).
770
771 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
772 and sequences work well. Unmapped character ordinals (ones which cause a
773 :exc:`LookupError`) are left untouched and are copied as-is.
774
Jeroen Ruigrok van der Werven47a7d702009-04-27 05:43:17 +0000775
Georg Brandl54a3faa2008-01-20 09:30:57 +0000776These are the MBCS codec APIs. They are currently only available on Windows and
777use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
778DBCS) is a class of encodings, not just one. The target encoding is defined by
779the user settings on the machine running the codec.
780
781.. % --- MBCS codecs for Windows --------------------------------------------
782
783
784.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
785
786 Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
787 Return *NULL* if an exception was raised by the codec.
788
789
790.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed)
791
792 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If
793 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode
794 trailing lead byte and the number of bytes that have been decoded will be stored
795 in *consumed*.
796
797
798.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
799
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000800 Encode the :ctype:`Py_UNICODE` buffer of the given size using MBCS and return
801 a Python bytes object. Return *NULL* if an exception was raised by the
802 codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000803
804
805.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)
806
Benjamin Petersonb6eba4f2009-01-13 23:14:04 +0000807 Encode a Unicode object using MBCS and return the result as Python bytes
808 object. Error handling is "strict". Return *NULL* if an exception was
809 raised by the codec.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000810
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000811For decoding file names and other environment strings, :cdata:`Py_FileSystemEncoding`
812should be used as the encoding, and ``"surrogateescape"`` should be used as the error
813handler. For encoding file names during argument parsing, the ``O&`` converter should
814be used, passsing PyUnicode_FSConverter as the conversion function:
815
816.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result)
817
818 Convert *obj* into *result*, using the file system encoding, and the ``surrogateescape``
819 error handler. *result* must be a ``PyObject*``, yielding a bytes or bytearray object
820 which must be released if it is no longer used.
821
822 .. versionadded:: 3.1
823
Georg Brandl54a3faa2008-01-20 09:30:57 +0000824.. % --- Methods & Slots ----------------------------------------------------
825
826
827.. _unicodemethodsandslots:
828
829Methods and Slot Functions
830^^^^^^^^^^^^^^^^^^^^^^^^^^
831
832The following APIs are capable of handling Unicode objects and strings on input
833(we refer to them as strings in the descriptions) and return Unicode objects or
834integers as appropriate.
835
836They all return *NULL* or ``-1`` if an exception occurs.
837
838
839.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)
840
841 Concat two strings giving a new Unicode string.
842
843
844.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
845
846 Split a string giving a list of Unicode strings. If sep is *NULL*, splitting
847 will be done at all whitespace substrings. Otherwise, splits occur at the given
848 separator. At most *maxsplit* splits will be done. If negative, no limit is
849 set. Separators are not included in the resulting list.
850
851
852.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
853
854 Split a Unicode string at line breaks, returning a list of Unicode strings.
855 CRLF is considered to be one line break. If *keepend* is 0, the Line break
856 characters are not included in the resulting strings.
857
858
859.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
860
861 Translate a string by applying a character mapping table to it and return the
862 resulting Unicode object.
863
864 The mapping table must map Unicode ordinal integers to Unicode ordinal integers
865 or None (causing deletion of the character).
866
867 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
868 and sequences work well. Unmapped character ordinals (ones which cause a
869 :exc:`LookupError`) are left untouched and are copied as-is.
870
871 *errors* has the usual meaning for codecs. It may be *NULL* which indicates to
872 use the default error handling.
873
874
875.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)
876
877 Join a sequence of strings using the given separator and return the resulting
878 Unicode string.
879
880
881.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
882
883 Return 1 if *substr* matches *str*[*start*:*end*] at the given tail end
884 (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match),
885 0 otherwise. Return ``-1`` if an error occurred.
886
887
888.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
889
890 Return the first position of *substr* in *str*[*start*:*end*] using the given
891 *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a
892 backward search). The return value is the index of the first match; a value of
893 ``-1`` indicates that no match was found, and ``-2`` indicates that an error
894 occurred and an exception has been set.
895
896
897.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
898
899 Return the number of non-overlapping occurrences of *substr* in
900 ``str[start:end]``. Return ``-1`` if an error occurred.
901
902
903.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
904
905 Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
906 return the resulting Unicode object. *maxcount* == -1 means replace all
907 occurrences.
908
909
910.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right)
911
912 Compare two strings and return -1, 0, 1 for less than, equal, and greater than,
913 respectively.
914
915
Benjamin Petersonc22ed142008-07-01 19:12:34 +0000916.. cfunction:: int PyUnicode_CompareWithASCIIString(PyObject *uni, char *string)
917
918 Compare a unicode object, *uni*, with *string* and return -1, 0, 1 for less
919 than, equal, and greater than, respectively.
920
921
Georg Brandl54a3faa2008-01-20 09:30:57 +0000922.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
923
924 Rich compare two unicode strings and return one of the following:
925
926 * ``NULL`` in case an exception was raised
927 * :const:`Py_True` or :const:`Py_False` for successful comparisons
928 * :const:`Py_NotImplemented` in case the type combination is unknown
929
930 Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
931 :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
932 with a :exc:`UnicodeDecodeError`.
933
934 Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
935 :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.
936
937
938.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)
939
940 Return a new string object from *format* and *args*; this is analogous to
941 ``format % args``. The *args* argument must be a tuple.
942
943
944.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element)
945
946 Check whether *element* is contained in *container* and return true or false
947 accordingly.
948
949 *element* has to coerce to a one element Unicode string. ``-1`` is returned if
950 there was an error.
951
952
953.. cfunction:: void PyUnicode_InternInPlace(PyObject **string)
954
955 Intern the argument *\*string* in place. The argument must be the address of a
956 pointer variable pointing to a Python unicode string object. If there is an
957 existing interned string that is the same as *\*string*, it sets *\*string* to
958 it (decrementing the reference count of the old string object and incrementing
959 the reference count of the interned string object), otherwise it leaves
960 *\*string* alone and interns it (incrementing its reference count).
961 (Clarification: even though there is a lot of talk about reference counts, think
962 of this function as reference-count-neutral; you own the object after the call
963 if and only if you owned it before the call.)
964
965
966.. cfunction:: PyObject* PyUnicode_InternFromString(const char *v)
967
968 A combination of :cfunc:`PyUnicode_FromString` and
969 :cfunc:`PyUnicode_InternInPlace`, returning either a new unicode string object
970 that has been interned, or a new ("owned") reference to an earlier interned
971 string object with the same value.
972