Debian Codegraph @

Doc/c-api/unicode.rst

raw
1 .. highlight:: c
2
3 .. _unicodeobjects:
4
5 Unicode Objects and Codecs
6 --------------------------
7
8 .. sectionauthor:: Marc-André Lemburg <[email protected]>
9 .. sectionauthor:: Georg Brandl <[email protected]>
10
11 Unicode Objects
12 ^^^^^^^^^^^^^^^
13
14 Since the implementation of :pep:`393` in Python 3.3, Unicode objects internally
15 use a variety of representations, in order to allow handling the complete range
16 of Unicode characters while staying memory efficient. There are special cases
17 for strings where all code points are below 128, 256, or 65536; otherwise, code
18 points must be below 1114112 (which is the full Unicode range).
19
20 UTF-8 representation is created on demand and cached in the Unicode object.
21
22 .. note::
23 The :c:type:`Py_UNICODE` representation has been removed since Python 3.12
24 with deprecated APIs.
25 See :pep:`623` for more information.
26
27
28 Unicode Type
29 """"""""""""
30
31 These are the basic Unicode object types used for the Unicode implementation in
32 Python:
33
34 .. c:type:: Py_UCS4
35 Py_UCS2
36 Py_UCS1
37
38 These types are typedefs for unsigned integer types wide enough to contain
39 characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with
40 single Unicode characters, use :c:type:`Py_UCS4`.
41
42 .. versionadded:: 3.3
43
44
45 .. c:type:: Py_UNICODE
46
47 This is a typedef of :c:type:`wchar_t`, which is a 16-bit type or 32-bit type
48 depending on the platform.
49
50 .. versionchanged:: 3.3
51 In previous versions, this was a 16-bit type or a 32-bit type depending on
52 whether you selected a "narrow" or "wide" Unicode version of Python at
53 build time.
54
55 .. deprecated-removed:: 3.13 3.15
56
57
58 .. c:type:: PyASCIIObject
59 PyCompactUnicodeObject
60 PyUnicodeObject
61
62 These subtypes of :c:type:`PyObject` represent a Python Unicode object. In
63 almost all cases, they shouldn't be used directly, since all API functions
64 that deal with Unicode objects take and return :c:type:`PyObject` pointers.
65
66 .. versionadded:: 3.3
67
68
69 .. c:var:: PyTypeObject PyUnicode_Type
70
71 This instance of :c:type:`PyTypeObject` represents the Python Unicode type.
72 It is exposed to Python code as ``str``.
73
74
75 .. c:var:: PyTypeObject PyUnicodeIter_Type
76
77 This instance of :c:type:`PyTypeObject` represents the Python Unicode
78 iterator type. It is used to iterate over Unicode string objects.
79
80
81 The following APIs are C macros and static inlined functions for fast checks and
82 access to internal read-only data of Unicode objects:
83
84 .. c:function:: int PyUnicode_Check(PyObject *obj)
85
86 Return true if the object *obj* is a Unicode object or an instance of a Unicode
87 subtype. This function always succeeds.
88
89
90 .. c:function:: int PyUnicode_CheckExact(PyObject *obj)
91
92 Return true if the object *obj* is a Unicode object, but not an instance of a
93 subtype. This function always succeeds.
94
95
96 .. c:function:: int PyUnicode_READY(PyObject *unicode)
97
98 Returns ``0``. This API is kept only for backward compatibility.
99
100 .. versionadded:: 3.3
101
102 .. deprecated:: 3.10
103 This API does nothing since Python 3.12.
104
105
106 .. c:function:: Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
107
108 Return the length of the Unicode string, in code points. *unicode* has to be a
109 Unicode object in the "canonical" representation (not checked).
110
111 .. versionadded:: 3.3
112
113
114 .. c:function:: Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *unicode)
115 Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *unicode)
116 Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *unicode)
117
118 Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4
119 integer types for direct character access. No checks are performed if the
120 canonical representation has the correct character size; use
121 :c:func:`PyUnicode_KIND` to select the right function.
122
123 .. versionadded:: 3.3
124
125
126 .. c:macro:: PyUnicode_1BYTE_KIND
127 PyUnicode_2BYTE_KIND
128 PyUnicode_4BYTE_KIND
129
130 Return values of the :c:func:`PyUnicode_KIND` macro.
131
132 .. versionadded:: 3.3
133
134 .. versionchanged:: 3.12
135 ``PyUnicode_WCHAR_KIND`` has been removed.
136
137
138 .. c:function:: int PyUnicode_KIND(PyObject *unicode)
139
140 Return one of the PyUnicode kind constants (see above) that indicate how many
141 bytes per character this Unicode object uses to store its data. *unicode* has to
142 be a Unicode object in the "canonical" representation (not checked).
143
144 .. versionadded:: 3.3
145
146
147 .. c:function:: void* PyUnicode_DATA(PyObject *unicode)
148
149 Return a void pointer to the raw Unicode buffer. *unicode* has to be a Unicode
150 object in the "canonical" representation (not checked).
151
152 .. versionadded:: 3.3
153
154
155 .. c:function:: void PyUnicode_WRITE(int kind, void *data, \
156 Py_ssize_t index, Py_UCS4 value)
157
158 Write into a canonical representation *data* (as obtained with
159 :c:func:`PyUnicode_DATA`). This function performs no sanity checks, and is
160 intended for usage in loops. The caller should cache the *kind* value and
161 *data* pointer as obtained from other calls. *index* is the index in
162 the string (starts at 0) and *value* is the new code point value which should
163 be written to that location.
164
165 .. versionadded:: 3.3
166
167
168 .. c:function:: Py_UCS4 PyUnicode_READ(int kind, void *data, \
169 Py_ssize_t index)
170
171 Read a code point from a canonical representation *data* (as obtained with
172 :c:func:`PyUnicode_DATA`). No checks or ready calls are performed.
173
174 .. versionadded:: 3.3
175
176
177 .. c:function:: Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
178
179 Read a character from a Unicode object *unicode*, which must be in the "canonical"
180 representation. This is less efficient than :c:func:`PyUnicode_READ` if you
181 do multiple consecutive reads.
182
183 .. versionadded:: 3.3
184
185
186 .. c:function:: Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)
187
188 Return the maximum code point that is suitable for creating another string
189 based on *unicode*, which must be in the "canonical" representation. This is
190 always an approximation but more efficient than iterating over the string.
191
192 .. versionadded:: 3.3
193
194
195 .. c:function:: int PyUnicode_IsIdentifier(PyObject *unicode)
196
197 Return ``1`` if the string is a valid identifier according to the language
198 definition, section :ref:`identifiers`. Return ``0`` otherwise.
199
200 .. versionchanged:: 3.9
201 The function does not call :c:func:`Py_FatalError` anymore if the string
202 is not ready.
203
204
205 Unicode Character Properties
206 """"""""""""""""""""""""""""
207
208 Unicode provides many different character properties. The most often needed ones
209 are available through these macros which are mapped to C functions depending on
210 the Python configuration.
211
212
213 .. c:function:: int Py_UNICODE_ISSPACE(Py_UCS4 ch)
214
215 Return ``1`` or ``0`` depending on whether *ch* is a whitespace character.
216
217
218 .. c:function:: int Py_UNICODE_ISLOWER(Py_UCS4 ch)
219
220 Return ``1`` or ``0`` depending on whether *ch* is a lowercase character.
221
222
223 .. c:function:: int Py_UNICODE_ISUPPER(Py_UCS4 ch)
224
225 Return ``1`` or ``0`` depending on whether *ch* is an uppercase character.
226
227
228 .. c:function:: int Py_UNICODE_ISTITLE(Py_UCS4 ch)
229
230 Return ``1`` or ``0`` depending on whether *ch* is a titlecase character.
231
232
233 .. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
234
235 Return ``1`` or ``0`` depending on whether *ch* is a linebreak character.
236
237
238 .. c:function:: int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
239
240 Return ``1`` or ``0`` depending on whether *ch* is a decimal character.
241
242
243 .. c:function:: int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
244
245 Return ``1`` or ``0`` depending on whether *ch* is a digit character.
246
247
248 .. c:function:: int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
249
250 Return ``1`` or ``0`` depending on whether *ch* is a numeric character.
251
252
253 .. c:function:: int Py_UNICODE_ISALPHA(Py_UCS4 ch)
254
255 Return ``1`` or ``0`` depending on whether *ch* is an alphabetic character.
256
257
258 .. c:function:: int Py_UNICODE_ISALNUM(Py_UCS4 ch)
259
260 Return ``1`` or ``0`` depending on whether *ch* is an alphanumeric character.
261
262
263 .. c:function:: int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
264
265 Return ``1`` or ``0`` depending on whether *ch* is a printable character,
266 in the sense of :meth:`str.isprintable`.
267
268
269 These APIs can be used for fast direct character conversions:
270
271
272 .. c:function:: Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
273
274 Return the character *ch* converted to lower case.
275
276
277 .. c:function:: Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
278
279 Return the character *ch* converted to upper case.
280
281
282 .. c:function:: Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
283
284 Return the character *ch* converted to title case.
285
286
287 .. c:function:: int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
288
289 Return the character *ch* converted to a decimal positive integer. Return
290 ``-1`` if this is not possible. This function does not raise exceptions.
291
292
293 .. c:function:: int Py_UNICODE_TODIGIT(Py_UCS4 ch)
294
295 Return the character *ch* converted to a single digit integer. Return ``-1`` if
296 this is not possible. This function does not raise exceptions.
297
298
299 .. c:function:: double Py_UNICODE_TONUMERIC(Py_UCS4 ch)
300
301 Return the character *ch* converted to a double. Return ``-1.0`` if this is not
302 possible. This function does not raise exceptions.
303
304
305 These APIs can be used to work with surrogates:
306
307 .. c:function:: int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)
308
309 Check if *ch* is a surrogate (``0xD800 <= ch <= 0xDFFF``).
310
311 .. c:function:: int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)
312
313 Check if *ch* is a high surrogate (``0xD800 <= ch <= 0xDBFF``).
314
315 .. c:function:: int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)
316
317 Check if *ch* is a low surrogate (``0xDC00 <= ch <= 0xDFFF``).
318
319 .. c:function:: Py_UCS4 Py_UNICODE_HIGH_SURROGATE(Py_UCS4 ch)
320
321 Return the high UTF-16 surrogate (``0xD800`` to ``0xDBFF``) for a Unicode
322 code point in the range ``[0x10000; 0x10FFFF]``.
323
324 .. c:function:: Py_UCS4 Py_UNICODE_LOW_SURROGATE(Py_UCS4 ch)
325
326 Return the low UTF-16 surrogate (``0xDC00`` to ``0xDFFF``) for a Unicode
327 code point in the range ``[0x10000; 0x10FFFF]``.
328
329 .. c:function:: Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)
330
331 Join two surrogate code points and return a single :c:type:`Py_UCS4` value.
332 *high* and *low* are respectively the leading and trailing surrogates in a
333 surrogate pair. *high* must be in the range ``[0xD800; 0xDBFF]`` and *low* must
334 be in the range ``[0xDC00; 0xDFFF]``.
335
336
337 Creating and accessing Unicode strings
338 """"""""""""""""""""""""""""""""""""""
339
340 To create Unicode objects and access their basic sequence properties, use these
341 APIs:
342
343 .. c:function:: PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
344
345 Create a new Unicode object. *maxchar* should be the true maximum code point
346 to be placed in the string. As an approximation, it can be rounded up to the
347 nearest value in the sequence 127, 255, 65535, 1114111.
348
349 This is the recommended way to allocate a new Unicode object. Objects
350 created using this function are not resizable.
351
352 On error, set an exception and return ``NULL``.
353
354 .. versionadded:: 3.3
355
356
357 .. c:function:: PyObject* PyUnicode_FromKindAndData(int kind, const void *buffer, \
358 Py_ssize_t size)
359
360 Create a new Unicode object with the given *kind* (possible values are
361 :c:macro:`PyUnicode_1BYTE_KIND` etc., as returned by
362 :c:func:`PyUnicode_KIND`). The *buffer* must point to an array of *size*
363 units of 1, 2 or 4 bytes per character, as given by the kind.
364
365 If necessary, the input *buffer* is copied and transformed into the
366 canonical representation. For example, if the *buffer* is a UCS4 string
367 (:c:macro:`PyUnicode_4BYTE_KIND`) and it consists only of codepoints in
368 the UCS1 range, it will be transformed into UCS1
369 (:c:macro:`PyUnicode_1BYTE_KIND`).
370
371 .. versionadded:: 3.3
372
373
374 .. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
375
376 Create a Unicode object from the char buffer *str*. The bytes will be
377 interpreted as being UTF-8 encoded. The buffer is copied into the new
378 object.
379 The return value might be a shared object, i.e. modification of the data is
380 not allowed.
381
382 This function raises :exc:`SystemError` when:
383
384 * *size* < 0,
385 * *str* is ``NULL`` and *size* > 0
386
387 .. versionchanged:: 3.12
388 *str* == ``NULL`` with *size* > 0 is not allowed anymore.
389
390
391 .. c:function:: PyObject *PyUnicode_FromString(const char *str)
392
393 Create a Unicode object from a UTF-8 encoded null-terminated char buffer
394 *str*.
395
396
397 .. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...)
398
399 Take a C :c:func:`printf`\ -style *format* string and a variable number of
400 arguments, calculate the size of the resulting Python Unicode string and return
401 a string with the values formatted into it. The variable arguments must be C
402 types and must correspond exactly to the format characters in the *format*
403 ASCII-encoded string.
404
405 A conversion specifier contains two or more characters and has the following
406 components, which must occur in this order:
407
408 #. The ``'%'`` character, which marks the start of the specifier.
409
410 #. Conversion flags (optional), which affect the result of some conversion
411 types.
412
413 #. Minimum field width (optional).
414 If specified as an ``'*'`` (asterisk), the actual width is given in the
415 next argument, which must be of type :c:expr:`int`, and the object to
416 convert comes after the minimum field width and optional precision.
417
418 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision.
419 If specified as ``'*'`` (an asterisk), the actual precision is given in
420 the next argument, which must be of type :c:expr:`int`, and the value to
421 convert comes after the precision.
422
423 #. Length modifier (optional).
424
425 #. Conversion type.
426
427 The conversion flag characters are:
428
429 .. tabularcolumns:: |l|L|
430
431 +-------+-------------------------------------------------------------+
432 | Flag | Meaning |
433 +=======+=============================================================+
434 | ``0`` | The conversion will be zero padded for numeric values. |
435 +-------+-------------------------------------------------------------+
436 | ``-`` | The converted value is left adjusted (overrides the ``0`` |
437 | | flag if both are given). |
438 +-------+-------------------------------------------------------------+
439
440 The length modifiers for following integer conversions (``d``, ``i``,
441 ``o``, ``u``, ``x``, or ``X``) specify the type of the argument
442 (:c:expr:`int` by default):
443
444 .. tabularcolumns:: |l|L|
445
446 +----------+-----------------------------------------------------+
447 | Modifier | Types |
448 +==========+=====================================================+
449 | ``l`` | :c:expr:`long` or :c:expr:`unsigned long` |
450 +----------+-----------------------------------------------------+
451 | ``ll`` | :c:expr:`long long` or :c:expr:`unsigned long long` |
452 +----------+-----------------------------------------------------+
453 | ``j`` | :c:type:`intmax_t` or :c:type:`uintmax_t` |
454 +----------+-----------------------------------------------------+
455 | ``z`` | :c:type:`size_t` or :c:type:`ssize_t` |
456 +----------+-----------------------------------------------------+
457 | ``t`` | :c:type:`ptrdiff_t` |
458 +----------+-----------------------------------------------------+
459
460 The length modifier ``l`` for following conversions ``s`` or ``V`` specify
461 that the type of the argument is :c:expr:`const wchar_t*`.
462
463 The conversion specifiers are:
464
465 .. list-table::
466 :widths: auto
467 :header-rows: 1
468
469 * - Conversion Specifier
470 - Type
471 - Comment
472
473 * - ``%``
474 - *n/a*
475 - The literal ``%`` character.
476
477 * - ``d``, ``i``
478 - Specified by the length modifier
479 - The decimal representation of a signed C integer.
480
481 * - ``u``
482 - Specified by the length modifier
483 - The decimal representation of an unsigned C integer.
484
485 * - ``o``
486 - Specified by the length modifier
487 - The octal representation of an unsigned C integer.
488
489 * - ``x``
490 - Specified by the length modifier
491 - The hexadecimal representation of an unsigned C integer (lowercase).
492
493 * - ``X``
494 - Specified by the length modifier
495 - The hexadecimal representation of an unsigned C integer (uppercase).
496
497 * - ``c``
498 - :c:expr:`int`
499 - A single character.
500
501 * - ``s``
502 - :c:expr:`const char*` or :c:expr:`const wchar_t*`
503 - A null-terminated C character array.
504
505 * - ``p``
506 - :c:expr:`const void*`
507 - The hex representation of a C pointer.
508 Mostly equivalent to ``printf("%p")`` except that it is guaranteed to
509 start with the literal ``0x`` regardless of what the platform's
510 ``printf`` yields.
511
512 * - ``A``
513 - :c:expr:`PyObject*`
514 - The result of calling :func:`ascii`.
515
516 * - ``U``
517 - :c:expr:`PyObject*`
518 - A Unicode object.
519
520 * - ``V``
521 - :c:expr:`PyObject*`, :c:expr:`const char*` or :c:expr:`const wchar_t*`
522 - A Unicode object (which may be ``NULL``) and a null-terminated
523 C character array as a second parameter (which will be used,
524 if the first parameter is ``NULL``).
525
526 * - ``S``
527 - :c:expr:`PyObject*`
528 - The result of calling :c:func:`PyObject_Str`.
529
530 * - ``R``
531 - :c:expr:`PyObject*`
532 - The result of calling :c:func:`PyObject_Repr`.
533
534 * - ``T``
535 - :c:expr:`PyObject*`
536 - Get the fully qualified name of an object type;
537 call :c:func:`PyType_GetFullyQualifiedName`.
538
539 * - ``#T``
540 - :c:expr:`PyObject*`
541 - Similar to ``T`` format, but use a colon (``:``) as separator between
542 the module name and the qualified name.
543
544 * - ``N``
545 - :c:expr:`PyTypeObject*`
546 - Get the fully qualified name of a type;
547 call :c:func:`PyType_GetFullyQualifiedName`.
548
549 * - ``#N``
550 - :c:expr:`PyTypeObject*`
551 - Similar to ``N`` format, but use a colon (``:``) as separator between
552 the module name and the qualified name.
553
554 .. note::
555 The width formatter unit is number of characters rather than bytes.
556 The precision formatter unit is number of bytes or :c:type:`wchar_t`
557 items (if the length modifier ``l`` is used) for ``"%s"`` and
558 ``"%V"`` (if the ``PyObject*`` argument is ``NULL``), and a number of
559 characters for ``"%A"``, ``"%U"``, ``"%S"``, ``"%R"`` and ``"%V"``
560 (if the ``PyObject*`` argument is not ``NULL``).
561
562 .. note::
563 Unlike to C :c:func:`printf` the ``0`` flag has effect even when
564 a precision is given for integer conversions (``d``, ``i``, ``u``, ``o``,
565 ``x``, or ``X``).
566
567 .. versionchanged:: 3.2
568 Support for ``"%lld"`` and ``"%llu"`` added.
569
570 .. versionchanged:: 3.3
571 Support for ``"%li"``, ``"%lli"`` and ``"%zi"`` added.
572
573 .. versionchanged:: 3.4
574 Support width and precision formatter for ``"%s"``, ``"%A"``, ``"%U"``,
575 ``"%V"``, ``"%S"``, ``"%R"`` added.
576
577 .. versionchanged:: 3.12
578 Support for conversion specifiers ``o`` and ``X``.
579 Support for length modifiers ``j`` and ``t``.
580 Length modifiers are now applied to all integer conversions.
581 Length modifier ``l`` is now applied to conversion specifiers ``s`` and ``V``.
582 Support for variable width and precision ``*``.
583 Support for flag ``-``.
584
585 An unrecognized format character now sets a :exc:`SystemError`.
586 In previous versions it caused all the rest of the format string to be
587 copied as-is to the result string, and any extra arguments discarded.
588
589 .. versionchanged:: 3.13
590 Support for ``%T``, ``%#T``, ``%N`` and ``%#N`` formats added.
591
592
593 .. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
594
595 Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two
596 arguments.
597
598
599 .. c:function:: PyObject* PyUnicode_FromObject(PyObject *obj)
600
601 Copy an instance of a Unicode subtype to a new true Unicode object if
602 necessary. If *obj* is already a true Unicode object (not a subtype),
603 return a new :term:`strong reference` to the object.
604
605 Objects other than Unicode or its subtypes will cause a :exc:`TypeError`.
606
607
608 .. c:function:: PyObject* PyUnicode_FromOrdinal(int ordinal)
609
610 Create a Unicode Object from the given Unicode code point *ordinal*.
611
612 The ordinal must be in ``range(0x110000)``. A :exc:`ValueError` is
613 raised in the case it is not.
614
615
616 .. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, \
617 const char *encoding, const char *errors)
618
619 Decode an encoded object *obj* to a Unicode object.
620
621 :class:`bytes`, :class:`bytearray` and other
622 :term:`bytes-like objects <bytes-like object>`
623 are decoded according to the given *encoding* and using the error handling
624 defined by *errors*. Both can be ``NULL`` to have the interface use the default
625 values (see :ref:`builtincodecs` for details).
626
627 All other objects, including Unicode objects, cause a :exc:`TypeError` to be
628 set.
629
630 The API returns ``NULL`` if there was an error. The caller is responsible for
631 decref'ing the returned objects.
632
633
634 .. c:function:: PyObject* PyUnicode_BuildEncodingMap(PyObject* string)
635
636 Return a mapping suitable for decoding a custom single-byte encoding.
637 Given a Unicode string *string* of up to 256 characters representing an encoding
638 table, returns either a compact internal mapping object or a dictionary
639 mapping character ordinals to byte values. Raises a :exc:`TypeError` and
640 return ``NULL`` on invalid input.
641 .. versionadded:: 3.2
642
643
644 .. c:function:: const char* PyUnicode_GetDefaultEncoding(void)
645
646 Return the name of the default string encoding, ``"utf-8"``.
647 See :func:`sys.getdefaultencoding`.
648
649 The returned string does not need to be freed, and is valid
650 until interpreter shutdown.
651
652
653 .. c:function:: Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
654
655 Return the length of the Unicode object, in code points.
656
657 On error, set an exception and return ``-1``.
658
659 .. versionadded:: 3.3
660
661
662 .. c:function:: Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, \
663 Py_ssize_t to_start, \
664 PyObject *from, \
665 Py_ssize_t from_start, \
666 Py_ssize_t how_many)
667
668 Copy characters from one Unicode object into another. This function performs
669 character conversion when necessary and falls back to :c:func:`!memcpy` if
670 possible. Returns ``-1`` and sets an exception on error, otherwise returns
671 the number of copied characters.
672
673 .. versionadded:: 3.3
674
675
676 .. c:function:: Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, \
677 Py_ssize_t length, Py_UCS4 fill_char)
678
679 Fill a string with a character: write *fill_char* into
680 ``unicode[start:start+length]``.
681
682 Fail if *fill_char* is bigger than the string maximum character, or if the
683 string has more than 1 reference.
684
685 Return the number of written character, or return ``-1`` and raise an
686 exception on error.
687
688 .. versionadded:: 3.3
689
690
691 .. c:function:: int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, \
692 Py_UCS4 character)
693
694 Write a character to a string. The string must have been created through
695 :c:func:`PyUnicode_New`. Since Unicode strings are supposed to be immutable,
696 the string must not be shared, or have been hashed yet.
697
698 This function checks that *unicode* is a Unicode object, that the index is
699 not out of bounds, and that the object can be modified safely (i.e. that it
700 its reference count is one).
701
702 Return ``0`` on success, ``-1`` on error with an exception set.
703
704 .. versionadded:: 3.3
705
706
707 .. c:function:: Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
708
709 Read a character from a string. This function checks that *unicode* is a
710 Unicode object and the index is not out of bounds, in contrast to
711 :c:func:`PyUnicode_READ_CHAR`, which performs no error checking.
712
713 Return character on success, ``-1`` on error with an exception set.
714
715 .. versionadded:: 3.3
716
717
718 .. c:function:: PyObject* PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, \
719 Py_ssize_t end)
720
721 Return a substring of *unicode*, from character index *start* (included) to
722 character index *end* (excluded). Negative indices are not supported.
723 On error, set an exception and return ``NULL``.
724
725 .. versionadded:: 3.3
726
727
728 .. c:function:: Py_UCS4* PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, \
729 Py_ssize_t buflen, int copy_null)
730
731 Copy the string *unicode* into a UCS4 buffer, including a null character, if
732 *copy_null* is set. Returns ``NULL`` and sets an exception on error (in
733 particular, a :exc:`SystemError` if *buflen* is smaller than the length of
734 *unicode*). *buffer* is returned on success.
735
736 .. versionadded:: 3.3
737
738
739 .. c:function:: Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *unicode)
740
741 Copy the string *unicode* into a new UCS4 buffer that is allocated using
742 :c:func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a
743 :exc:`MemoryError` set. The returned buffer always has an extra
744 null code point appended.
745
746 .. versionadded:: 3.3
747
748
749 Locale Encoding
750 """""""""""""""
751
752 The current locale encoding can be used to decode text from the operating
753 system.
754
755 .. c:function:: PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, \
756 Py_ssize_t length, \
757 const char *errors)
758
759 Decode a string from UTF-8 on Android and VxWorks, or from the current
760 locale encoding on other platforms. The supported
761 error handlers are ``"strict"`` and ``"surrogateescape"``
762 (:pep:`383`). The decoder uses ``"strict"`` error handler if
763 *errors* is ``NULL``. *str* must end with a null character but
764 cannot contain embedded null characters.
765
766 Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` to decode a string from
767 the :term:`filesystem encoding and error handler`.
768
769 This function ignores the :ref:`Python UTF-8 Mode <utf8-mode>`.
770
771 .. seealso::
772
773 The :c:func:`Py_DecodeLocale` function.
774
775 .. versionadded:: 3.3
776
777 .. versionchanged:: 3.7
778 The function now also uses the current locale encoding for the
779 ``surrogateescape`` error handler, except on Android. Previously, :c:func:`Py_DecodeLocale`
780 was used for the ``surrogateescape``, and the current locale encoding was
781 used for ``strict``.
782
783
784 .. c:function:: PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors)
785
786 Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string
787 length using :c:func:`!strlen`.
788
789 .. versionadded:: 3.3
790
791
792 .. c:function:: PyObject* PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
793
794 Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current
795 locale encoding on other platforms. The
796 supported error handlers are ``"strict"`` and ``"surrogateescape"``
797 (:pep:`383`). The encoder uses ``"strict"`` error handler if
798 *errors* is ``NULL``. Return a :class:`bytes` object. *unicode* cannot
799 contain embedded null characters.
800
801 Use :c:func:`PyUnicode_EncodeFSDefault` to encode a string to the
802 :term:`filesystem encoding and error handler`.
803
804 This function ignores the :ref:`Python UTF-8 Mode <utf8-mode>`.
805
806 .. seealso::
807
808 The :c:func:`Py_EncodeLocale` function.
809
810 .. versionadded:: 3.3
811
812 .. versionchanged:: 3.7
813 The function now also uses the current locale encoding for the
814 ``surrogateescape`` error handler, except on Android. Previously,
815 :c:func:`Py_EncodeLocale`
816 was used for the ``surrogateescape``, and the current locale encoding was
817 used for ``strict``.
818
819
820 File System Encoding
821 """"""""""""""""""""
822
823 Functions encoding to and decoding from the :term:`filesystem encoding and
824 error handler` (:pep:`383` and :pep:`529`).
825
826 To encode file names to :class:`bytes` during argument parsing, the ``"O&"``
827 converter should be used, passing :c:func:`!PyUnicode_FSConverter` as the
828 conversion function:
829
830 .. c:function:: int PyUnicode_FSConverter(PyObject* obj, void* result)
831
832 :ref:`PyArg_Parse\* converter <arg-parsing>`: encode :class:`str` objects -- obtained directly or
833 through the :class:`os.PathLike` interface -- to :class:`bytes` using
834 :c:func:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is.
835 *result* must be an address of a C variable of type :c:expr:`PyObject*`
836 (or :c:expr:`PyBytesObject*`).
837 On success, set the variable to a new :term:`strong reference` to
838 a :ref:`bytes object <bytesobjects>` which must be released
839 when it is no longer used and return a non-zero value
840 (:c:macro:`Py_CLEANUP_SUPPORTED`).
841 Embedded null bytes are not allowed in the result.
842 On failure, return ``0`` with an exception set.
843
844 If *obj* is ``NULL``, the function releases a strong reference
845 stored in the variable referred by *result* and returns ``1``.
846
847 .. versionadded:: 3.1
848
849 .. versionchanged:: 3.6
850 Accepts a :term:`path-like object`.
851
852 To decode file names to :class:`str` during argument parsing, the ``"O&"``
853 converter should be used, passing :c:func:`!PyUnicode_FSDecoder` as the
854 conversion function:
855
856 .. c:function:: int PyUnicode_FSDecoder(PyObject* obj, void* result)
857
858 :ref:`PyArg_Parse\* converter <arg-parsing>`: decode :class:`bytes` objects -- obtained either
859 directly or indirectly through the :class:`os.PathLike` interface -- to
860 :class:`str` using :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str`
861 objects are output as-is.
862 *result* must be an address of a C variable of type :c:expr:`PyObject*`
863 (or :c:expr:`PyUnicodeObject*`).
864 On success, set the variable to a new :term:`strong reference` to
865 a :ref:`Unicode object <unicodeobjects>` which must be released
866 when it is no longer used and return a non-zero value
867 (:c:macro:`Py_CLEANUP_SUPPORTED`).
868 Embedded null characters are not allowed in the result.
869 On failure, return ``0`` with an exception set.
870
871 If *obj* is ``NULL``, release the strong reference
872 to the object referred to by *result* and return ``1``.
873
874 .. versionadded:: 3.2
875
876 .. versionchanged:: 3.6
877 Accepts a :term:`path-like object`.
878
879
880 .. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
881
882 Decode a string from the :term:`filesystem encoding and error handler`.
883
884 If you need to decode a string from the current locale encoding, use
885 :c:func:`PyUnicode_DecodeLocaleAndSize`.
886
887 .. seealso::
888
889 The :c:func:`Py_DecodeLocale` function.
890
891 .. versionchanged:: 3.6
892 The :term:`filesystem error handler <filesystem encoding and error
893 handler>` is now used.
894
895
896 .. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *str)
897
898 Decode a null-terminated string from the :term:`filesystem encoding and
899 error handler`.
900
901 If the string length is known, use
902 :c:func:`PyUnicode_DecodeFSDefaultAndSize`.
903
904 .. versionchanged:: 3.6
905 The :term:`filesystem error handler <filesystem encoding and error
906 handler>` is now used.
907
908
909 .. c:function:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode)
910
911 Encode a Unicode object to the :term:`filesystem encoding and error
912 handler`, and return :class:`bytes`. Note that the resulting :class:`bytes`
913 object can contain null bytes.
914
915 If you need to encode a string to the current locale encoding, use
916 :c:func:`PyUnicode_EncodeLocale`.
917
918 .. seealso::
919
920 The :c:func:`Py_EncodeLocale` function.
921
922 .. versionadded:: 3.2
923
924 .. versionchanged:: 3.6
925 The :term:`filesystem error handler <filesystem encoding and error
926 handler>` is now used.
927
928 wchar_t Support
929 """""""""""""""
930
931 :c:type:`wchar_t` support for platforms which support it:
932
933 .. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
934
935 Create a Unicode object from the :c:type:`wchar_t` buffer *wstr* of the given *size*.
936 Passing ``-1`` as the *size* indicates that the function must itself compute the length,
937 using :c:func:`!wcslen`.
938 Return ``NULL`` on failure.
939
940
941 .. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
942
943 Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. At most
944 *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing
945 null termination character). Return the number of :c:type:`wchar_t` characters
946 copied or ``-1`` in case of an error.
947
948 When *wstr* is ``NULL``, instead return the *size* that would be required
949 to store all of *unicode* including a terminating null.
950
951 Note that the resulting :c:expr:`wchar_t*`
952 string may or may not be null-terminated. It is the responsibility of the caller
953 to make sure that the :c:expr:`wchar_t*` string is null-terminated in case this is
954 required by the application. Also, note that the :c:expr:`wchar_t*` string
955 might contain null characters, which would cause the string to be truncated
956 when used with most C functions.
957
958
959 .. c:function:: wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
960
961 Convert the Unicode object to a wide character string. The output string
962 always ends with a null character. If *size* is not ``NULL``, write the number
963 of wide characters (excluding the trailing null termination character) into
964 *\*size*. Note that the resulting :c:type:`wchar_t` string might contain
965 null characters, which would cause the string to be truncated when used with
966 most C functions. If *size* is ``NULL`` and the :c:expr:`wchar_t*` string
967 contains null characters a :exc:`ValueError` is raised.
968
969 Returns a buffer allocated by :c:macro:`PyMem_New` (use
970 :c:func:`PyMem_Free` to free it) on success. On error, returns ``NULL``
971 and *\*size* is undefined. Raises a :exc:`MemoryError` if memory allocation
972 is failed.
973
974 .. versionadded:: 3.2
975
976 .. versionchanged:: 3.7
977 Raises a :exc:`ValueError` if *size* is ``NULL`` and the :c:expr:`wchar_t*`
978 string contains null characters.
979
980
981 .. _builtincodecs:
982
983 Built-in Codecs
984 ^^^^^^^^^^^^^^^
985
986 Python provides a set of built-in codecs which are written in C for speed. All of
987 these codecs are directly usable via the following functions.
988
989 Many of the following APIs take two arguments encoding and errors, and they
990 have the same semantics as the ones of the built-in :func:`str` string object
991 constructor.
992
993 Setting encoding to ``NULL`` causes the default encoding to be used
994 which is UTF-8. The file system calls should use
995 :c:func:`PyUnicode_FSConverter` for encoding file names. This uses the
996 :term:`filesystem encoding and error handler` internally.
997
998 Error handling is set by errors which may also be set to ``NULL`` meaning to use
999 the default handling defined for the codec. Default error handling for all
1000 built-in codecs is "strict" (:exc:`ValueError` is raised).
1001
1002 The codecs all use a similar interface. Only deviations from the following
1003 generic ones are documented for simplicity.
1004
1005
1006 Generic Codecs
1007 """"""""""""""
1008
1009 These are the generic codec APIs:
1010
1011
1012 .. c:function:: PyObject* PyUnicode_Decode(const char *str, Py_ssize_t size, \
1013 const char *encoding, const char *errors)
1014
1015 Create a Unicode object by decoding *size* bytes of the encoded string *str*.
1016 *encoding* and *errors* have the same meaning as the parameters of the same name
1017 in the :func:`str` built-in function. The codec to be used is looked up
1018 using the Python codec registry. Return ``NULL`` if an exception was raised by
1019 the codec.
1020
1021
1022 .. c:function:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, \
1023 const char *encoding, const char *errors)
1024
1025 Encode a Unicode object and return the result as Python bytes object.
1026 *encoding* and *errors* have the same meaning as the parameters of the same
1027 name in the Unicode :meth:`~str.encode` method. The codec to be used is looked up
1028 using the Python codec registry. Return ``NULL`` if an exception was raised by
1029 the codec.
1030
1031
1032 UTF-8 Codecs
1033 """"""""""""
1034
1035 These are the UTF-8 codec APIs:
1036
1037
1038 .. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
1039
1040 Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
1041 *str*. Return ``NULL`` if an exception was raised by the codec.
1042
1043
1044 .. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, \
1045 const char *errors, Py_ssize_t *consumed)
1046
1047 If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF8`. If
1048 *consumed* is not ``NULL``, trailing incomplete UTF-8 byte sequences will not be
1049 treated as an error. Those bytes will not be decoded and the number of bytes
1050 that have been decoded will be stored in *consumed*.
1051
1052
1053 .. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode)
1054
1055 Encode a Unicode object using UTF-8 and return the result as Python bytes
1056 object. Error handling is "strict". Return ``NULL`` if an exception was
1057 raised by the codec.
1058
1059 The function fails if the string contains surrogate code points
1060 (``U+D800`` - ``U+DFFF``).
1061
1062
1063 .. c:function:: const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
1064
1065 Return a pointer to the UTF-8 encoding of the Unicode object, and
1066 store the size of the encoded representation (in bytes) in *size*. The
1067 *size* argument can be ``NULL``; in this case no size will be stored. The
1068 returned buffer always has an extra null byte appended (not included in
1069 *size*), regardless of whether there are any other null code points.
1070
1071 On error, set an exception, set *size* to ``-1`` (if it's not NULL) and
1072 return ``NULL``.
1073
1074 The function fails if the string contains surrogate code points
1075 (``U+D800`` - ``U+DFFF``).
1076
1077 This caches the UTF-8 representation of the string in the Unicode object, and
1078 subsequent calls will return a pointer to the same buffer. The caller is not
1079 responsible for deallocating the buffer. The buffer is deallocated and
1080 pointers to it become invalid when the Unicode object is garbage collected.
1081
1082 .. versionadded:: 3.3
1083
1084 .. versionchanged:: 3.7
1085 The return type is now ``const char *`` rather of ``char *``.
1086
1087 .. versionchanged:: 3.10
1088 This function is a part of the :ref:`limited API <limited-c-api>`.
1089
1090
1091 .. c:function:: const char* PyUnicode_AsUTF8(PyObject *unicode)
1092
1093 As :c:func:`PyUnicode_AsUTF8AndSize`, but does not store the size.
1094
1095 .. warning::
1096
1097 This function does not have any special behavior for
1098 `null characters <https://en.wikipedia.org/wiki/Null_character>`_ embedded within
1099 *unicode*. As a result, strings containing null characters will remain in the returned
1100 string, which some C functions might interpret as the end of the string, leading to
1101 truncation. If truncation is an issue, it is recommended to use :c:func:`PyUnicode_AsUTF8AndSize`
1102 instead.
1103
1104 .. versionadded:: 3.3
1105
1106 .. versionchanged:: 3.7
1107 The return type is now ``const char *`` rather of ``char *``.
1108
1109
1110 UTF-32 Codecs
1111 """""""""""""
1112
1113 These are the UTF-32 codec APIs:
1114
1115
1116 .. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, \
1117 const char *errors, int *byteorder)
1118
1119 Decode *size* bytes from a UTF-32 encoded buffer string and return the
1120 corresponding Unicode object. *errors* (if non-``NULL``) defines the error
1121 handling. It defaults to "strict".
1122
1123 If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte
1124 order::
1125
1126 *byteorder == -1: little endian
1127 *byteorder == 0: native order
1128 *byteorder == 1: big endian
1129
1130 If ``*byteorder`` is zero, and the first four bytes of the input data are a
1131 byte order mark (BOM), the decoder switches to this byte order and the BOM is
1132 not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or
1133 ``1``, any byte order mark is copied to the output.
1134
1135 After completion, *\*byteorder* is set to the current byte order at the end
1136 of input data.
1137
1138 If *byteorder* is ``NULL``, the codec starts in native order mode.
1139
1140 Return ``NULL`` if an exception was raised by the codec.
1141
1142
1143 .. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, \
1144 const char *errors, int *byteorder, Py_ssize_t *consumed)
1145
1146 If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If
1147 *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF32Stateful` will not treat
1148 trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
1149 by four) as an error. Those bytes will not be decoded and the number of bytes
1150 that have been decoded will be stored in *consumed*.
1151
1152
1153 .. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
1154
1155 Return a Python byte string using the UTF-32 encoding in native byte
1156 order. The string always starts with a BOM mark. Error handling is "strict".
1157 Return ``NULL`` if an exception was raised by the codec.
1158
1159
1160 UTF-16 Codecs
1161 """""""""""""
1162
1163 These are the UTF-16 codec APIs:
1164
1165
1166 .. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, \
1167 const char *errors, int *byteorder)
1168
1169 Decode *size* bytes from a UTF-16 encoded buffer string and return the
1170 corresponding Unicode object. *errors* (if non-``NULL``) defines the error
1171 handling. It defaults to "strict".
1172
1173 If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte
1174 order::
1175
1176 *byteorder == -1: little endian
1177 *byteorder == 0: native order
1178 *byteorder == 1: big endian
1179
1180 If ``*byteorder`` is zero, and the first two bytes of the input data are a
1181 byte order mark (BOM), the decoder switches to this byte order and the BOM is
1182 not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or
1183 ``1``, any byte order mark is copied to the output (where it will result in
1184 either a ``\ufeff`` or a ``\ufffe`` character).
1185
1186 After completion, ``*byteorder`` is set to the current byte order at the end
1187 of input data.
1188
1189 If *byteorder* is ``NULL``, the codec starts in native order mode.
1190
1191 Return ``NULL`` if an exception was raised by the codec.
1192
1193
1194 .. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, \
1195 const char *errors, int *byteorder, Py_ssize_t *consumed)
1196
1197 If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If
1198 *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF16Stateful` will not treat
1199 trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
1200 split surrogate pair) as an error. Those bytes will not be decoded and the
1201 number of bytes that have been decoded will be stored in *consumed*.
1202
1203
1204 .. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
1205
1206 Return a Python byte string using the UTF-16 encoding in native byte
1207 order. The string always starts with a BOM mark. Error handling is "strict".
1208 Return ``NULL`` if an exception was raised by the codec.
1209
1210
1211 UTF-7 Codecs
1212 """"""""""""
1213
1214 These are the UTF-7 codec APIs:
1215
1216
1217 .. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
1218
1219 Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string
1220 *str*. Return ``NULL`` if an exception was raised by the codec.
1221
1222
1223 .. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, \
1224 const char *errors, Py_ssize_t *consumed)
1225
1226 If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF7`. If
1227 *consumed* is not ``NULL``, trailing incomplete UTF-7 base-64 sections will not
1228 be treated as an error. Those bytes will not be decoded and the number of
1229 bytes that have been decoded will be stored in *consumed*.
1230
1231
1232 Unicode-Escape Codecs
1233 """""""""""""""""""""
1234
1235 These are the "Unicode Escape" codec APIs:
1236
1237
1238 .. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *str, \
1239 Py_ssize_t size, const char *errors)
1240
1241 Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
1242 string *str*. Return ``NULL`` if an exception was raised by the codec.
1243
1244
1245 .. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
1246
1247 Encode a Unicode object using Unicode-Escape and return the result as a
1248 bytes object. Error handling is "strict". Return ``NULL`` if an exception was
1249 raised by the codec.
1250
1251
1252 Raw-Unicode-Escape Codecs
1253 """""""""""""""""""""""""
1254
1255 These are the "Raw Unicode Escape" codec APIs:
1256
1257
1258 .. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *str, \
1259 Py_ssize_t size, const char *errors)
1260
1261 Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
1262 encoded string *str*. Return ``NULL`` if an exception was raised by the codec.
1263
1264
1265 .. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
1266
1267 Encode a Unicode object using Raw-Unicode-Escape and return the result as
1268 a bytes object. Error handling is "strict". Return ``NULL`` if an exception
1269 was raised by the codec.
1270
1271
1272 Latin-1 Codecs
1273 """"""""""""""
1274
1275 These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
1276 ordinals and only these are accepted by the codecs during encoding.
1277
1278
1279 .. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
1280
1281 Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
1282 *str*. Return ``NULL`` if an exception was raised by the codec.
1283
1284
1285 .. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
1286
1287 Encode a Unicode object using Latin-1 and return the result as Python bytes
1288 object. Error handling is "strict". Return ``NULL`` if an exception was
1289 raised by the codec.
1290
1291
1292 ASCII Codecs
1293 """"""""""""
1294
1295 These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
1296 codes generate errors.
1297
1298
1299 .. c:function:: PyObject* PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
1300
1301 Create a Unicode object by decoding *size* bytes of the ASCII encoded string
1302 *str*. Return ``NULL`` if an exception was raised by the codec.
1303
1304
1305 .. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
1306
1307 Encode a Unicode object using ASCII and return the result as Python bytes
1308 object. Error handling is "strict". Return ``NULL`` if an exception was
1309 raised by the codec.
1310
1311
1312 Character Map Codecs
1313 """"""""""""""""""""
1314
1315 This codec is special in that it can be used to implement many different codecs
1316 (and this is in fact what was done to obtain most of the standard codecs
1317 included in the :mod:`!encodings` package). The codec uses mappings to encode and
1318 decode characters. The mapping objects provided must support the
1319 :meth:`~object.__getitem__` mapping interface; dictionaries and sequences work well.
1320
1321 These are the mapping codec APIs:
1322
1323 .. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, \
1324 PyObject *mapping, const char *errors)
1325
1326 Create a Unicode object by decoding *size* bytes of the encoded string *str*
1327 using the given *mapping* object. Return ``NULL`` if an exception was raised
1328 by the codec.
1329
1330 If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else
1331 *mapping* must map bytes ordinals (integers in the range from 0 to 255)
1332 to Unicode strings, integers (which are then interpreted as Unicode
1333 ordinals) or ``None``. Unmapped data bytes -- ones which cause a
1334 :exc:`LookupError`, as well as ones which get mapped to ``None``,
1335 ``0xFFFE`` or ``'\ufffe'``, are treated as undefined mappings and cause
1336 an error.
1337
1338
1339 .. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
1340
1341 Encode a Unicode object using the given *mapping* object and return the
1342 result as a bytes object. Error handling is "strict". Return ``NULL`` if an
1343 exception was raised by the codec.
1344
1345 The *mapping* object must map Unicode ordinal integers to bytes objects,
1346 integers in the range from 0 to 255 or ``None``. Unmapped character
1347 ordinals (ones which cause a :exc:`LookupError`) as well as mapped to
1348 ``None`` are treated as "undefined mapping" and cause an error.
1349
1350
1351 The following codec API is special in that maps Unicode to Unicode.
1352
1353 .. c:function:: PyObject* PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
1354
1355 Translate a string by applying a character mapping table to it and return the
1356 resulting Unicode object. Return ``NULL`` if an exception was raised by the
1357 codec.
1358
1359 The mapping table must map Unicode ordinal integers to Unicode ordinal integers
1360 or ``None`` (causing deletion of the character).
1361
1362 Mapping tables need only provide the :meth:`~object.__getitem__` interface; dictionaries
1363 and sequences work well. Unmapped character ordinals (ones which cause a
1364 :exc:`LookupError`) are left untouched and are copied as-is.
1365
1366 *errors* has the usual meaning for codecs. It may be ``NULL`` which indicates to
1367 use the default error handling.
1368
1369
1370 MBCS codecs for Windows
1371 """""""""""""""""""""""
1372
1373 These are the MBCS codec APIs. They are currently only available on Windows and
1374 use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
1375 DBCS) is a class of encodings, not just one. The target encoding is defined by
1376 the user settings on the machine running the codec.
1377
1378 .. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
1379
1380 Create a Unicode object by decoding *size* bytes of the MBCS encoded string *str*.
1381 Return ``NULL`` if an exception was raised by the codec.
1382
1383
1384 .. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, \
1385 const char *errors, Py_ssize_t *consumed)
1386
1387 If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If
1388 *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeMBCSStateful` will not decode
1389 trailing lead byte and the number of bytes that have been decoded will be stored
1390 in *consumed*.
1391
1392
1393 .. c:function:: PyObject* PyUnicode_DecodeCodePageStateful(int code_page, const char *str, \
1394 Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
1395
1396 Similar to :c:func:`PyUnicode_DecodeMBCSStateful`, except uses the code page
1397 specified by *code_page*.
1398
1399
1400 .. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)
1401
1402 Encode a Unicode object using MBCS and return the result as Python bytes
1403 object. Error handling is "strict". Return ``NULL`` if an exception was
1404 raised by the codec.
1405
1406
1407 .. c:function:: PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
1408
1409 Encode the Unicode object using the specified code page and return a Python
1410 bytes object. Return ``NULL`` if an exception was raised by the codec. Use
1411 :c:macro:`!CP_ACP` code page to get the MBCS encoder.
1412
1413 .. versionadded:: 3.3
1414
1415
1416 .. _unicodemethodsandslots:
1417
1418 Methods and Slot Functions
1419 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1420
1421 The following APIs are capable of handling Unicode objects and strings on input
1422 (we refer to them as strings in the descriptions) and return Unicode objects or
1423 integers as appropriate.
1424
1425 They all return ``NULL`` or ``-1`` if an exception occurs.
1426
1427
1428 .. c:function:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)
1429
1430 Concat two strings giving a new Unicode string.
1431
1432
1433 .. c:function:: PyObject* PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
1434
1435 Split a string giving a list of Unicode strings. If *sep* is ``NULL``, splitting
1436 will be done at all whitespace substrings. Otherwise, splits occur at the given
1437 separator. At most *maxsplit* splits will be done. If negative, no limit is
1438 set. Separators are not included in the resulting list.
1439
1440 On error, return ``NULL`` with an exception set.
1441
1442 Equivalent to :py:meth:`str.split`.
1443
1444
1445 .. c:function:: PyObject* PyUnicode_RSplit(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
1446
1447 Similar to :c:func:`PyUnicode_Split`, but splitting will be done beginning
1448 at the end of the string.
1449
1450 On error, return ``NULL`` with an exception set.
1451
1452 Equivalent to :py:meth:`str.rsplit`.
1453
1454
1455 .. c:function:: PyObject* PyUnicode_Splitlines(PyObject *unicode, int keepends)
1456
1457 Split a Unicode string at line breaks, returning a list of Unicode strings.
1458 CRLF is considered to be one line break. If *keepends* is ``0``, the Line break
1459 characters are not included in the resulting strings.
1460
1461
1462 .. c:function:: PyObject* PyUnicode_Partition(PyObject *unicode, PyObject *sep)
1463
1464 Split a Unicode string at the first occurrence of *sep*, and return
1465 a 3-tuple containing the part before the separator, the separator itself,
1466 and the part after the separator. If the separator is not found,
1467 return a 3-tuple containing the string itself, followed by two empty strings.
1468
1469 *sep* must not be empty.
1470
1471 On error, return ``NULL`` with an exception set.
1472
1473 Equivalent to :py:meth:`str.partition`.
1474
1475
1476 .. c:function:: PyObject* PyUnicode_RPartition(PyObject *unicode, PyObject *sep)
1477
1478 Similar to :c:func:`PyUnicode_Partition`, but split a Unicode string at the
1479 last occurrence of *sep*. If the separator is not found, return a 3-tuple
1480 containing two empty strings, followed by the string itself.
1481
1482 *sep* must not be empty.
1483
1484 On error, return ``NULL`` with an exception set.
1485
1486 Equivalent to :py:meth:`str.rpartition`.
1487
1488
1489 .. c:function:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)
1490
1491 Join a sequence of strings using the given *separator* and return the resulting
1492 Unicode string.
1493
1494
1495 .. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, \
1496 Py_ssize_t start, Py_ssize_t end, int direction)
1497
1498 Return ``1`` if *substr* matches ``unicode[start:end]`` at the given tail end
1499 (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` a suffix match),
1500 ``0`` otherwise. Return ``-1`` if an error occurred.
1501
1502
1503 .. c:function:: Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, \
1504 Py_ssize_t start, Py_ssize_t end, int direction)
1505
1506 Return the first position of *substr* in ``unicode[start:end]`` using the given
1507 *direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a
1508 backward search). The return value is the index of the first match; a value of
1509 ``-1`` indicates that no match was found, and ``-2`` indicates that an error
1510 occurred and an exception has been set.
1511
1512
1513 .. c:function:: Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, \
1514 Py_ssize_t start, Py_ssize_t end, int direction)
1515
1516 Return the first position of the character *ch* in ``unicode[start:end]`` using
1517 the given *direction* (*direction* == ``1`` means to do a forward search,
1518 *direction* == ``-1`` a backward search). The return value is the index of the
1519 first match; a value of ``-1`` indicates that no match was found, and ``-2``
1520 indicates that an error occurred and an exception has been set.
1521
1522 .. versionadded:: 3.3
1523
1524 .. versionchanged:: 3.7
1525 *start* and *end* are now adjusted to behave like ``unicode[start:end]``.
1526
1527
1528 .. c:function:: Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, \
1529 Py_ssize_t start, Py_ssize_t end)
1530
1531 Return the number of non-overlapping occurrences of *substr* in
1532 ``unicode[start:end]``. Return ``-1`` if an error occurred.
1533
1534
1535 .. c:function:: PyObject* PyUnicode_Replace(PyObject *unicode, PyObject *substr, \
1536 PyObject *replstr, Py_ssize_t maxcount)
1537
1538 Replace at most *maxcount* occurrences of *substr* in *unicode* with *replstr* and
1539 return the resulting Unicode object. *maxcount* == ``-1`` means replace all
1540 occurrences.
1541
1542
1543 .. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right)
1544
1545 Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, and greater than,
1546 respectively.
1547
1548 This function returns ``-1`` upon failure, so one should call
1549 :c:func:`PyErr_Occurred` to check for errors.
1550
1551
1552 .. c:function:: int PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *string, Py_ssize_t size)
1553
1554 Compare a Unicode object with a char buffer which is interpreted as
1555 being UTF-8 or ASCII encoded and return true (``1``) if they are equal,
1556 or false (``0``) otherwise.
1557 If the Unicode object contains surrogate code points
1558 (``U+D800`` - ``U+DFFF``) or the C string is not valid UTF-8,
1559 false (``0``) is returned.
1560
1561 This function does not raise exceptions.
1562
1563 .. versionadded:: 3.13
1564
1565
1566 .. c:function:: int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)
1567
1568 Similar to :c:func:`PyUnicode_EqualToUTF8AndSize`, but compute *string*
1569 length using :c:func:`!strlen`.
1570 If the Unicode object contains null characters, false (``0``) is returned.
1571
1572 .. versionadded:: 3.13
1573
1574
1575 .. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
1576
1577 Compare a Unicode object, *unicode*, with *string* and return ``-1``, ``0``, ``1`` for less
1578 than, equal, and greater than, respectively. It is best to pass only
1579 ASCII-encoded strings, but the function interprets the input string as
1580 ISO-8859-1 if it contains non-ASCII characters.
1581
1582 This function does not raise exceptions.
1583
1584
1585 .. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
1586
1587 Rich compare two Unicode strings and return one of the following:
1588
1589 * ``NULL`` in case an exception was raised
1590 * :c:data:`Py_True` or :c:data:`Py_False` for successful comparisons
1591 * :c:data:`Py_NotImplemented` in case the type combination is unknown
1592
1593 Possible values for *op* are :c:macro:`Py_GT`, :c:macro:`Py_GE`, :c:macro:`Py_EQ`,
1594 :c:macro:`Py_NE`, :c:macro:`Py_LT`, and :c:macro:`Py_LE`.
1595
1596
1597 .. c:function:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)
1598
1599 Return a new string object from *format* and *args*; this is analogous to
1600 ``format % args``.
1601
1602
1603 .. c:function:: int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
1604
1605 Check whether *substr* is contained in *unicode* and return true or false
1606 accordingly.
1607
1608 *substr* has to coerce to a one element Unicode string. ``-1`` is returned
1609 if there was an error.
1610
1611
1612 .. c:function:: void PyUnicode_InternInPlace(PyObject **p_unicode)
1613
1614 Intern the argument :c:expr:`*p_unicode` in place. The argument must be the address of a
1615 pointer variable pointing to a Python Unicode string object. If there is an
1616 existing interned string that is the same as :c:expr:`*p_unicode`, it sets :c:expr:`*p_unicode` to
1617 it (releasing the reference to the old string object and creating a new
1618 :term:`strong reference` to the interned string object), otherwise it leaves
1619 :c:expr:`*p_unicode` alone and interns it.
1620
1621 (Clarification: even though there is a lot of talk about references, think
1622 of this function as reference-neutral. You must own the object you pass in;
1623 after the call you no longer own the passed-in reference, but you newly own
1624 the result.)
1625
1626 This function never raises an exception.
1627 On error, it leaves its argument unchanged without interning it.
1628
1629 Instances of subclasses of :py:class:`str` may not be interned, that is,
1630 :c:expr:`PyUnicode_CheckExact(*p_unicode)` must be true. If it is not,
1631 then -- as with any other error -- the argument is left unchanged.
1632
1633 Note that interned strings are not “immortal”.
1634 You must keep a reference to the result to benefit from interning.
1635
1636
1637 .. c:function:: PyObject* PyUnicode_InternFromString(const char *str)
1638
1639 A combination of :c:func:`PyUnicode_FromString` and
1640 :c:func:`PyUnicode_InternInPlace`, meant for statically allocated strings.
1641
1642 Return a new ("owned") reference to either a new Unicode string object
1643 that has been interned, or an earlier interned string object with the
1644 same value.
1645
1646 Python may keep a reference to the result, or make it :term:`immortal`,
1647 preventing it from being garbage-collected promptly.
1648 For interning an unbounded number of different strings, such as ones coming
1649 from user input, prefer calling :c:func:`PyUnicode_FromString` and
1650 :c:func:`PyUnicode_InternInPlace` directly.
1651
1652