# Objetos y códecs unicode

## Objetos unicode

Desde la implementación del PEP 393 en Python 3.3, los objetos Unicode utilizan internamente una variedad de representaciones, para permitir el manejo del rango completo de caracteres Unicode mientras se mantiene la eficiencia de memoria. Hay casos especiales para cadenas de caracteres donde todos los puntos de código están por debajo de 128, 256 o 65536; de lo contrario, los puntos de código deben estar por debajo de 1114112 (que es el rango completo de Unicode).

UTF-8 representation is created on demand and cached in the Unicode object.

Nota

The `Py_UNICODE` representation has been removed since Python 3.12 with deprecated APIs. See PEP 623 for more information.

### Tipo unicode

Estos son los tipos básicos de objetos Unicode utilizados para la implementación de Unicode en Python:

PyTypeObject PyUnicode_Type
  Part of the Stable ABI.

  This instance of `PyTypeObject` represents the Python Unicode type. It is exposed to Python code as `str`.

PyTypeObject PyUnicodeIter_Type
  Part of the Stable ABI.

  This instance of `PyTypeObject` represents the Python Unicode iterator type. It is used to iterate over Unicode string objects.

type Py_UCS4
type Py_UCS2
type Py_UCS1
  Part of the Stable ABI.

  Estos tipos son definiciones de tipo (typedefs) para los tipos “enteros sin signo” (unsigned int) lo suficientemente anchos como para contener caracteres de 32 bits, 16 bits y 8 bits, respectivamente. Cuando se trate con caracteres Unicode individuales, use `Py_UCS4`.

  Added in version 3.3.

type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject

  Estos subtipos de `PyObject` representan un objeto Python Unicode. En casi todos los casos, no deben usarse directamente, ya que todas las funciones API que se ocupan de objetos Unicode toman y retornan punteros `PyObject`.

  Added in version 3.3.

The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of Unicode objects:

int PyUnicode_Check(PyObject *obj)

  Return true if the object obj is a Unicode object or an instance of a Unicode subtype. This function always succeeds.

int PyUnicode_CheckExact(PyObject *obj)

  Return true if the object obj is a Unicode object, but not an instance of a subtype. This function always succeeds.

Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)

  Return the length of the Unicode string, in code points. unicode has to be a Unicode object in the «canonical» representation (not checked).

  Added in version 3.3.

Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)

  Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct character access. No checks are performed if the canonical representation has the correct character size; use `PyUnicode_KIND()` to select the right function.

  Added in version 3.3.

PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND

  Retorna los valores de la macro `PyUnicode_KIND()`.

  Added in version 3.3.

  Distinto en la versión 3.12: `PyUnicode_WCHAR_KIND` has been removed.

int PyUnicode_KIND(PyObject *unicode)

  Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Unicode object uses to store its data. unicode has to be a Unicode object in the «canonical» representation (not checked).

  Added in version 3.3.

void *PyUnicode_DATA(PyObject *unicode)

  Return a void pointer to the raw Unicode buffer. unicode has to be a Unicode object in the «canonical» representation (not checked).

  Added in version 3.3.

void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)

  Write the code point value to the given zero-based index in a string.

  The kind value and data pointer must have been obtained from a string using `PyUnicode_KIND()` and `PyUnicode_DATA()` respectively. You must hold a reference to that string while calling `PyUnicode_WRITE()`. All requirements of `PyUnicode_WriteChar()` also apply.

  The function performs no checks for any of its requirements, and is intended for usage in loops.

  Added in version 3.3.

Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)

  Lee un punto de código de una representación canónica data (obtenido con `PyUnicode_DATA()`). No se realizan verificaciones ni llamadas preparadas.

  Added in version 3.3.

Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)

  Read a character from a Unicode object unicode, which must be in the «canonical» representation. This is less efficient than `PyUnicode_READ()` if you do multiple consecutive reads.

  Added in version 3.3.

Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)

  Return the maximum code point that is suitable for creating another string based on unicode, which must be in the «canonical» representation. This is always an approximation but more efficient than iterating over the string.

  Added in version 3.3.

int PyUnicode_IsIdentifier(PyObject *unicode)
  Part of the Stable ABI.

  Retorna `1` si la cadena de caracteres es un identificador válido de acuerdo con la definición del lenguaje, sección Names (identifiers and keywords). Retorna `0` de lo contrario.

  Distinto en la versión 3.9: La función ya no llama a `Py_FatalError()` si la cadena de caracteres no está lista.

unsigned int PyUnicode_IS_ASCII(PyObject *unicode)

  Return true if the string only contains ASCII characters. Equivalent to `str.isascii()`.

  Added in version 3.2.

Py_hash_t PyUnstable_Unicode_GET_CACHED_HASH(PyObject *str)
  This is Unstable API. It may change without warning in minor releases.

  If the hash of str, as returned by `PyObject_Hash()`, has been cached and is immediately available, return it. Otherwise, return `-1` without setting an exception.

  If str is not a string (that is, if `PyUnicode_Check(obj)` is false), the behavior is undefined.

  This function never fails with an exception.

  Note that there are no guarantees on when an object’s hash is cached, and the (non-)existence of a cached hash does not imply that the string has any other properties.

### Propiedades de caracteres Unicode

Unicode proporciona muchas propiedades de caracteres diferentes. Los que se necesitan con mayor frecuencia están disponibles a través de estas macros que se asignan a las funciones de C según la configuración de Python.

int Py_UNICODE_ISSPACE(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter de espacio en blanco.

int Py_UNICODE_ISLOWER(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter en minúscula.

int Py_UNICODE_ISUPPER(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter en mayúscula.

int Py_UNICODE_ISTITLE(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter en caso de título (titlecase).

int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter de salto de línea.

int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter decimal o no.

int Py_UNICODE_ISDIGIT(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter de dígitos.

int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter numérico.

int Py_UNICODE_ISALPHA(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter alfabético.

int Py_UNICODE_ISALNUM(Py_UCS4 ch)

  Retorna `1` o `0` dependiendo de si ch es un carácter alfanumérico.

int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)

  Return `1` or `0` depending on whether ch is a printable character, in the sense of `str.isprintable()`.

Estas API se pueden usar para conversiones caracteres rápidas y directos:

Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)

  Retorna el carácter ch convertido a minúsculas.

Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)

  Retorna el carácter ch convertido a mayúsculas.

Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)

  Retorna el carácter ch convertido a formato de título (titlecase).

int Py_UNICODE_TODECIMAL(Py_UCS4 ch)

  Return the character ch converted to a decimal positive integer. Return `-1` if this is not possible. This function does not raise exceptions.

int Py_UNICODE_TODIGIT(Py_UCS4 ch)

  Return the character ch converted to a single digit integer. Return `-1` if this is not possible. This function does not raise exceptions.

double Py_UNICODE_TONUMERIC(Py_UCS4 ch)

  Return the character ch converted to a double. Return `-1.0` if this is not possible. This function does not raise exceptions.

Estas API se pueden usar para trabajar con sustitutos:

int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)

  Comprueba si ch es un sustituto (`0xD800 <= ch <= 0xDFFF`).

int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)

  Comprueba si ch es un sustituto alto (`0xD800 <= ch <= 0xDFFF`).

int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)

  Comprueba si ch es un sustituto bajo (`0xD800 <= ch <= 0xDFFF`).

Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)

  Join two surrogate code points and return a single `Py_UCS4` value. high and low are respectively the leading and trailing surrogates in a surrogate pair. high must be in the range [0xD800; 0xDBFF] and low must be in the range [0xDC00; 0xDFFF].

### Creando y accediendo a cadenas de caracteres Unicode

Para crear objetos Unicode y acceder a sus propiedades de secuencia básicas, use estas API:

PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
  Return value: New reference.

  Crea un nuevo objeto Unicode. maxchar debe ser el punto de código máximo que se colocará en la cadena de caracteres. Como una aproximación, se puede redondear al valor más cercano en la secuencia 127, 255, 65535, 1114111.

  On error, set an exception and return `NULL`.

  After creation, the string can be filled by `PyUnicode_WriteChar()`, `PyUnicode_CopyCharacters()`, `PyUnicode_Fill()`, `PyUnicode_WRITE()` or similar. Since strings are supposed to be immutable, take care to not “use” the result while it is being modified. In particular, before it’s filled with its final contents, a string:

  - must not be hashed,

  - must not be `converted to UTF-8`, or another non-«canonical» representation,

  - must not have its reference count changed,

  - must not be shared with code that might do one of the above.

  This list is not exhaustive. Avoiding these uses is your responsibility; Python does not always check these requirements.

  To avoid accidentally exposing a partially-written string object, prefer using the `PyUnicodeWriter` API, or one of the `PyUnicode_From*` functions below.

  Added in version 3.3.

PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
  Return value: New reference.

  Crea un nuevo objeto Unicode con el tipo kind dado (los valores posibles son `PyUnicode_1BYTE_KIND` etc., según lo retornado por `PyUnicode_KIND()`). El búfer debe apuntar a un vector (array) de tamaño unidades de 1, 2 o 4 bytes por carácter, según el tipo.

  Si es necesario, la entrada buffer se copia y se transforma en la representación canónica. Por ejemplo, si el buffer es una cadena de caracteres UCS4 (`PyUnicode_4BYTE_KIND`) y consta solo de puntos de código en el rango UCS1, se transformará en UCS1 (`PyUnicode_1BYTE_KIND`).

  Added in version 3.3.

PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object from the char buffer str. The bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might be a shared object, i.e. modification of the data is not allowed.

  This function raises `SystemError` when:

  - size < 0,

  - str is `NULL` and size > 0

  Distinto en la versión 3.12: str == `NULL` with size > 0 is not allowed anymore.

PyObject *PyUnicode_FromString(const char *str)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object from a UTF-8 encoded null-terminated char buffer str.

PyObject *PyUnicode_FromFormat(const char *format, ...)
  Return value: New reference. Part of the Stable ABI.

  Take a C `printf()`-style format string and a variable number of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the format ASCII-encoded string.

  A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The `'%'` character, which marks the start of the specifier.

  2. Conversion flags (optional), which affect the result of some conversion types.

  3. Minimum field width (optional). If specified as an `'*'` (asterisk), the actual width is given in the next argument, which must be of type int, and the object to convert comes after the minimum field width and optional precision.

  4. Precision (optional), given as a `'.'` (dot) followed by the precision. If specified as `'*'` (an asterisk), the actual precision is given in the next argument, which must be of type int, and the value to convert comes after the precision.

  5. Length modifier (optional).

  6. Conversion type.

  The conversion flag characters are:

  Flag | Meaning
  --- | ---
  `0` | The conversion will be zero padded for numeric values.
  `-` | The converted value is left adjusted (overrides the `0` flag if both are given).

  The length modifiers for following integer conversions (`d`, `i`, `o`, `u`, `x`, or `X`) specify the type of the argument (int by default):

  Modifier | Types
  --- | ---
  `l` | long or unsigned long
  `ll` | long long or unsigned long long
  `j` | `intmax_t` or `uintmax_t`
  `z` | `size_t` or `ssize_t`
  `t` | `ptrdiff_t`

  The length modifier `l` for following conversions `s` or `V` specify that the type of the argument is const wchar_t*.

  The conversion specifiers are:

  Conversion Specifier | Tipo | Comentario
  --- | --- | ---
  `%` | n/a | The literal `%` character.
  `d`, `i` | Specified by the length modifier | The decimal representation of a signed C integer.
  `u` | Specified by the length modifier | The decimal representation of an unsigned C integer.
  `o` | Specified by the length modifier | The octal representation of an unsigned C integer.
  `x` | Specified by the length modifier | The hexadecimal representation of an unsigned C integer (lowercase).
  `X` | Specified by the length modifier | The hexadecimal representation of an unsigned C integer (uppercase).
  `c` | int | A single character.
  `s` | const char* or const wchar_t* | Un arreglo de caracteres de C terminada en nulo.
  `p` | const void* | The hex representation of a C pointer. Mostly equivalent to `printf("%p")` except that it is guaranteed to start with the literal `0x` regardless of what the platform’s `printf` yields.
  `A` | PyObject* | El resultado de llamar `ascii()`.
  `U` | PyObject* | Un objeto unicode.
  `V` | PyObject*, const char* or const wchar_t* | Un objeto Unicode (que puede ser `NULL`) y un arreglo de caracteres de C terminada en nulo como segundo parámetro (que se utilizará, si el primer parámetro es `NULL`).
  `S` | PyObject* | El resultado de llamar `PyObject_Str()`.
  `R` | PyObject* | El resultado de llamar `PyObject_Repr()`.
  `T` | PyObject* | Get the fully qualified name of an object type; call `PyType_GetFullyQualifiedName()`.
  `#T` | PyObject* | Similar to `T` format, but use a colon (`:`) as separator between the module name and the qualified name.
  `N` | PyTypeObject* | Get the fully qualified name of a type; call `PyType_GetFullyQualifiedName()`.
  `#N` | PyTypeObject* | Similar to `N` format, but use a colon (`:`) as separator between the module name and the qualified name.

  Nota

  The width formatter unit is number of characters rather than bytes. The precision formatter unit is number of bytes or `wchar_t` items (if the length modifier `l` is used) for `"%s"` and `"%V"` (if the `PyObject*` argument is `NULL`), and a number of characters for `"%A"`, `"%U"`, `"%S"`, `"%R"` and `"%V"` (if the `PyObject*` argument is not `NULL`).

  Nota

  Unlike to C `printf()` the `0` flag has effect even when a precision is given for integer conversions (`d`, `i`, `u`, `o`, `x`, or `X`).

  Distinto en la versión 3.2: Soporte agregado para `"%lld"` y `"%llu"`.

  Distinto en la versión 3.3: Soporte agregado para `"%li"`, `"%lli"` y `"%zi"`.

  Distinto en la versión 3.4: Soporte agregado para formateadores de anchura y precisión para `"%s"`, `"%A"`, `"%U"`, `"%V"`, `"%S"`, `"%R"`.

  Distinto en la versión 3.12: Support for conversion specifiers `o` and `X`. Support for length modifiers `j` and `t`. Length modifiers are now applied to all integer conversions. Length modifier `l` is now applied to conversion specifiers `s` and `V`. Support for variable width and precision `*`. Support for flag `-`.

  An unrecognized format character now sets a `SystemError`. In previous versions it caused all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded.

  Distinto en la versión 3.13: Support for `%T`, `%#T`, `%N` and `%#N` formats added.

PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
  Return value: New reference. Part of the Stable ABI.

  Idéntico a `PyUnicode_FromFormat()` excepto que toma exactamente dos argumentos.

PyObject *PyUnicode_FromObject(PyObject *obj)
  Return value: New reference. Part of the Stable ABI.

  Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return a new strong reference to the object.

  Los objetos que no sean Unicode o sus subtipos causarán un `TypeError`.

PyObject *PyUnicode_FromOrdinal(int ordinal)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode Object from the given Unicode code point ordinal.

  The ordinal must be in `range(0x110000)`. A `ValueError` is raised in the case it is not.

PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Decodifica un objeto codificado obj en un objeto Unicode.

  `bytes`, `bytearray` y otros los objetos similares a bytes se decodifican de acuerdo con el encoding dado y utilizan el manejo de errores definido por errors. Ambos pueden ser `NULL` para que la interfaz use los valores predeterminados (ver Códecs incorporados para más detalles).

  Todos los demás objetos, incluidos los objetos Unicode, hacen que se establezca un `TypeError`.

  La API retorna `NULL` si hubo un error. La entidad que hace la llamadas es la responsable de desreferenciar los objetos retornados.

void PyUnicode_Append(PyObject **p_left, PyObject *right)
  Part of the Stable ABI.

  Append the string right to the end of p_left. p_left must point to a strong reference to a Unicode object; `PyUnicode_Append()` releases («steals») this reference.

  On error, set *p_left to `NULL` and set an exception.

  On success, set *p_left to a new strong reference to the result.

void PyUnicode_AppendAndDel(PyObject **p_left, PyObject *right)
  Part of the Stable ABI.

  The function is similar to `PyUnicode_Append()`, with the only difference being that it decrements the reference count of right by one.

PyObject *PyUnicode_BuildEncodingMap(PyObject *string)
  Return value: New reference. Part of the Stable ABI.

  Return a mapping suitable for decoding a custom single-byte encoding. Given a Unicode string string of up to 256 characters representing an encoding table, returns either a compact internal mapping object or a dictionary mapping character ordinals to byte values. Raises a `TypeError` and return `NULL` on invalid input.

  Added in version 3.2.

const char *PyUnicode_GetDefaultEncoding(void)
  Part of the Stable ABI.

  Return the name of the default string encoding, `"utf-8"`. See `sys.getdefaultencoding()`.

  The returned string does not need to be freed, and is valid until interpreter shutdown.

Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
  Part of the Stable ABI since version 3.7.

  Retorna la longitud del objeto Unicode, en puntos de código.

  On error, set an exception and return `-1`.

  Added in version 3.3.

Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)

  Copy characters from one Unicode object into another. This function performs character conversion when necessary and falls back to `memcpy()` if possible. Returns `-1` and sets an exception on error, otherwise returns the number of copied characters.

  The string must not have been “used” yet. See `PyUnicode_New()` for details.

  Added in version 3.3.

int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length);
  Part of the Stable ABI.

  Resize a Unicode object *unicode to the new length in code points.

  Try to resize the string in place (which is usually faster than allocating a new string and copying characters), or create a new string.

  *unicode is modified to point to the new (resized) object and `0` is returned on success. Otherwise, `-1` is returned and an exception is set, and *unicode is left untouched.

  The function doesn’t check string content, the result may not be a string in canonical representation.

Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

  Rellena una cadena con un carácter: escriba fill_char en `unicode[inicio:inicio+longitud]`.

  Falla si fill_char es más grande que el carácter máximo de la cadena, o si la cadena tiene más de 1 referencia.

  The string must not have been “used” yet. See `PyUnicode_New()` for details.

  Retorna el número de caracteres escritos o retorna `-1` y lanza una excepción en caso de error.

  Added in version 3.3.

int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
  Part of the Stable ABI since version 3.7.

  Write a character to the string unicode at the zero-based index. Return `0` on success, `-1` on error with an exception set.

  This function checks that unicode is a Unicode object, that the index is not out of bounds, and that the object’s reference count is one). See `PyUnicode_WRITE()` for a version that skips these checks, making them your responsibility.

  The string must not have been “used” yet. See `PyUnicode_New()` for details.

  Added in version 3.3.

Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
  Part of the Stable ABI since version 3.7.

  Read a character from a string. This function checks that unicode is a Unicode object and the index is not out of bounds, in contrast to `PyUnicode_READ_CHAR()`, which performs no error checking.

  Return character on success, `-1` on error with an exception set.

  Added in version 3.3.

PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
  Return value: New reference. Part of the Stable ABI since version 3.7.

  Return a substring of unicode, from character index start (included) to character index end (excluded). Negative indices are not supported. On error, set an exception and return `NULL`.

  Added in version 3.3.

Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
  Part of the Stable ABI since version 3.7.

  Copy the string unicode into a UCS4 buffer, including a null character, if copy_null is set. Returns `NULL` and sets an exception on error (in particular, a `SystemError` if buflen is smaller than the length of unicode). buffer is returned on success.

  Added in version 3.3.

Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *unicode)
  Part of the Stable ABI since version 3.7.

  Copy the string unicode into a new UCS4 buffer that is allocated using `PyMem_Malloc()`. If this fails, `NULL` is returned with a `MemoryError` set. The returned buffer always has an extra null code point appended.

  Added in version 3.3.

### Codificación regional

La codificación local actual se puede utilizar para decodificar texto del sistema operativo.

PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
  Return value: New reference. Part of the Stable ABI since version 3.7.

  Decodifica una cadena de caracteres UTF-8 en Android y VxWorks, o de la codificación de configuración regional actual en otras plataformas. Los manejadores de errores admitidos son `"estricto"` y `"subrogateescape"` (PEP 383). El decodificador usa el controlador de errores `"estricto"` si errors es `NULL`. str debe terminar con un carácter nulo pero no puede contener caracteres nulos incrustados.

  Use `PyUnicode_DecodeFSDefaultAndSize()` to decode a string from the filesystem encoding and error handler.

  Esta función ignora el modo Python UTF-8.

  Ver también

  La función `Py_DecodeLocale()`.

  Added in version 3.3.

  Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el controlador de errores `subrogateescape`, excepto en Android. Anteriormente, `Py_DecodeLocale()` se usaba para el `subrogateescape`, y la codificación local actual se usaba para `estricto`.

PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
  Return value: New reference. Part of the Stable ABI since version 3.7.

  Similar to `PyUnicode_DecodeLocaleAndSize()`, but compute the string length using `strlen()`.

  Added in version 3.3.

PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
  Return value: New reference. Part of the Stable ABI since version 3.7.

  Codifica un objeto Unicode UTF-8 en Android y VxWorks, o en la codificación local actual en otras plataformas. Los manejadores de errores admitidos son `"estricto"` y `"subrogateescape"` (PEP 383). El codificador utiliza el controlador de errores `"estricto"` si errors es `NULL`. Retorna un objeto `bytes`. unicode no puede contener caracteres nulos incrustados.

  Use `PyUnicode_EncodeFSDefault()` to encode a string to the filesystem encoding and error handler.

  Esta función ignora el modo Python UTF-8.

  Ver también

  La función `Py_EncodeLocale()`.

  Added in version 3.3.

  Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el controlador de errores `subrogateescape`, excepto en Android. Anteriormente, `Py_EncodeLocale()` se usaba para el `subrogateescape`, y la codificación local actual se usaba para `estricto`.

### Codificación del sistema de archivos

Functions encoding to and decoding from the filesystem encoding and error handler (PEP 383 and PEP 529).

To encode file names to `bytes` during argument parsing, the `"O&"` converter should be used, passing `PyUnicode_FSConverter()` as the conversion function:

int PyUnicode_FSConverter(PyObject *obj, void *result)
  Part of the Stable ABI.

  PyArg_Parse* converter: encode `str` objects – obtained directly or through the `os.PathLike` interface – to `bytes` using `PyUnicode_EncodeFSDefault()`; `bytes` objects are output as-is. result must be an address of a C variable of type PyObject* (or PyBytesObject*). On success, set the variable to a new strong reference to a bytes object which must be released when it is no longer used and return a non-zero value (`Py_CLEANUP_SUPPORTED`). Embedded null bytes are not allowed in the result. On failure, return `0` with an exception set.

  If obj is `NULL`, the function releases a strong reference stored in the variable referred by result and returns `1`.

  Added in version 3.1.

  Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).

To decode file names to `str` during argument parsing, the `"O&"` converter should be used, passing `PyUnicode_FSDecoder()` as the conversion function:

int PyUnicode_FSDecoder(PyObject *obj, void *result)
  Part of the Stable ABI.

  PyArg_Parse* converter: decode `bytes` objects – obtained either directly or indirectly through the `os.PathLike` interface – to `str` using `PyUnicode_DecodeFSDefaultAndSize()`; `str` objects are output as-is. result must be an address of a C variable of type PyObject* (or PyUnicodeObject*). On success, set the variable to a new strong reference to a Unicode object which must be released when it is no longer used and return a non-zero value (`Py_CLEANUP_SUPPORTED`). Embedded null characters are not allowed in the result. On failure, return `0` with an exception set.

  If obj is `NULL`, release the strong reference to the object referred to by result and return `1`.

  Added in version 3.2.

  Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).

PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
  Return value: New reference. Part of the Stable ABI.

  Decodifica una cadena desde el codificador de sistema de archivos y gestor de errores.

  If you need to decode a string from the current locale encoding, use `PyUnicode_DecodeLocaleAndSize()`.

  Ver también

  La función `Py_DecodeLocale()`.

  Distinto en la versión 3.6: The filesystem error handler is now used.

PyObject *PyUnicode_DecodeFSDefault(const char *str)
  Return value: New reference. Part of the Stable ABI.

  Decodifica una cadena terminada en nulo desde el codificador de sistema de archivos y gestor de errores.

  If the string length is known, use `PyUnicode_DecodeFSDefaultAndSize()`.

  Distinto en la versión 3.6: The filesystem error handler is now used.

PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Encode a Unicode object to the filesystem encoding and error handler, and return `bytes`. Note that the resulting `bytes` object can contain null bytes.

  If you need to encode a string to the current locale encoding, use `PyUnicode_EncodeLocale()`.

  Ver también

  La función `Py_EncodeLocale()`.

  Added in version 3.2.

  Distinto en la versión 3.6: The filesystem error handler is now used.

### soporte wchar_t

`wchar_t` support for platforms which support it:

PyObject *PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object from the `wchar_t` buffer wstr of the given size. Passing `-1` as the size indicates that the function must itself compute the length, using `wcslen()`. Return `NULL` on failure.

Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
  Part of the Stable ABI.

  Copy the Unicode object contents into the `wchar_t` buffer wstr. At most size `wchar_t` characters are copied (excluding a possibly trailing null termination character). Return the number of `wchar_t` characters copied or `-1` in case of an error.

  When wstr is `NULL`, instead return the size that would be required to store all of unicode including a terminating null.

  Note that the resulting wchar_t* string may or may not be null-terminated. It is the responsibility of the caller to make sure that the wchar_t* string is null-terminated in case this is required by the application. Also, note that the wchar_t* string might contain null characters, which would cause the string to be truncated when used with most C functions.

wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
  Part of the Stable ABI since version 3.7.

  Convert the Unicode object to a wide character string. The output string always ends with a null character. If size is not `NULL`, write the number of wide characters (excluding the trailing null termination character) into *size. Note that the resulting `wchar_t` string might contain null characters, which would cause the string to be truncated when used with most C functions. If size is `NULL` and the wchar_t* string contains null characters a `ValueError` is raised.

  Returns a buffer allocated by `PyMem_New` (use `PyMem_Free()` to free it) on success. On error, returns `NULL` and *size is undefined. Raises a `MemoryError` if memory allocation is failed.

  Added in version 3.2.

  Distinto en la versión 3.7: Raises a `ValueError` if size is `NULL` and the wchar_t* string contains null characters.

## Códecs incorporados

Python proporciona un conjunto de códecs integrados que están escritos en C para mayor velocidad. Todos estos códecs se pueden usar directamente a través de las siguientes funciones.

Muchas de las siguientes API toman dos argumentos de encoding y errors, y tienen la misma semántica que las del constructor de objetos de cadena incorporado `str()`.

Setting encoding to `NULL` causes the default encoding to be used which is UTF-8. The file system calls should use `PyUnicode_FSConverter()` for encoding file names. This uses the filesystem encoding and error handler internally.

El manejo de errores se establece mediante errors que también pueden establecerse en `NULL`, lo que significa usar el manejo predeterminado definido para el códec. El manejo de errores predeterminado para todos los códecs integrados es «estricto» (se lanza `ValueError`).

The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.

### Códecs genéricos

The following macro is provided:

Py_UNICODE_REPLACEMENT_CHARACTER

  The Unicode code point `U+FFFD` (replacement character).

  This Unicode character is used as the replacement character during decoding if the errors argument is set to «replace».

Estas son las APIs de códecs genéricos:

PyObject *PyUnicode_Decode(const char *str, Py_ssize_t size, const char *encoding, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the encoded string str. encoding and errors have the same meaning as the parameters of the same name in the `str()` built-in function. The codec to be used is looked up using the Python codec registry. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode y retorna el resultado como un objeto de bytes de Python. encoding y errors tienen el mismo significado que los parámetros del mismo nombre en el método Unicode `encode()`. El códec que se utilizará se busca utilizando el registro de códec Python. Retorna `NULL` si el códec provocó una excepción.

### Códecs UTF-8

Estas son las APIs del códec UTF-8:

PyObject *PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the UTF-8 encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI.

  Si consumed es `NULL`, se comporta como `PyUnicode_DecodeUTF8()`. Si consumed no es `NULL`, las secuencias de bytes UTF-8 incompletas no se tratarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará en consumed.

PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando UTF-8 y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

  The function fails if the string contains surrogate code points (`U+D800` - `U+DFFF`).

const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
  Part of the Stable ABI since version 3.10.

  Retorna un puntero a la codificación UTF-8 del objeto Unicode y almacena el tamaño de la representación codificada (en bytes) en size. El argumento size puede ser `NULL`; en este caso no se almacenará el tamaño. El búfer retornado siempre tiene un byte nulo adicional agregado (no incluido en size), independientemente de si hay otros puntos de código nulo.

  On error, set an exception, set size to `-1` (if it’s not NULL) and return `NULL`.

  The function fails if the string contains surrogate code points (`U+D800` - `U+DFFF`).

  This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected.

  Added in version 3.3.

  Distinto en la versión 3.7: El tipo de retorno ahora es `const char *` en lugar de `char *`.

  Distinto en la versión 3.10: This function is a part of the limited API.

const char *PyUnicode_AsUTF8(PyObject *unicode)

  Como `PyUnicode_AsUTF8AndSize()`, pero no almacena el tamaño.

  Advertencia

  This function does not have any special behavior for null characters embedded within unicode. As a result, strings containing null characters will remain in the returned string, which some C functions might interpret as the end of the string, leading to truncation. If truncation is an issue, it is recommended to use `PyUnicode_AsUTF8AndSize()` instead.

  Added in version 3.3.

  Distinto en la versión 3.7: El tipo de retorno ahora es `const char *` en lugar de `char *`.

### Códecs UTF-32

Estas son las APIs de códecs para UTF-32:

PyObject *PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
  Return value: New reference. Part of the Stable ABI.

  Decodifica size bytes de una cadena de búfer codificada UTF-32 y retorna el objeto Unicode correspondiente. errors (si no es `NULL`) define el manejo de errores. Su valor predeterminado es «estricto».

  Si byteorder no es `NULL`, el decodificador comienza a decodificar utilizando el orden de bytes dado:

      *byteorder == -1: little endian
      *byteorder == 0:  native order
      *byteorder == 1:  big endian

  Si `*byteorder` es cero, y los primeros cuatro bytes de los datos de entrada son una marca de orden de bytes (BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode resultante. Si `*byteorder` es `-1` o `1`, cualquier marca de orden de bytes se copia en la salida.

  Una vez completado, *byteorder se establece en el orden de bytes actual al final de los datos de entrada.

  Si byteorder es `NULL`, el códec se inicia en modo de orden nativo.

  Retorna `NULL` si el códec provocó una excepción.

PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI.

  Si consumed es `NULL`, se comporta como `PyUnicode_DecodeUTF32()`. Si consumed no es `NULL`, `PyUnicode_DecodeUTF32Stateful()` no tratará las secuencias de bytes UTF-32 incompletas finales (como un número de bytes no divisible por cuatro) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará en consumed.

PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Retorna una cadena de bytes de Python usando la codificación UTF-32 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs UTF-16

Estas son las APIs de códecs para UTF-16:

PyObject *PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
  Return value: New reference. Part of the Stable ABI.

  Decodifica size bytes de una cadena de caracteres de búfer codificada UTF-16 y retorna el objeto Unicode correspondiente. errors (si no es `NULL`) define el manejo de errores. Su valor predeterminado es «estricto».

  Si byteorder no es `NULL`, el decodificador comienza a decodificar utilizando el orden de bytes dado:

      *byteorder == -1: little endian
      *byteorder == 0:  native order
      *byteorder == 1:  big endian

  Si `*byteorder` es cero, y los primeros dos bytes de los datos de entrada son una marca de orden de bytes (BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode resultante. Si `*byteorder` es `-1` o `1`, cualquier marca de orden de bytes se copia en la salida (donde dará como resultado un `\ufeff` o un carácter `\ufffe`).

  After completion, `*byteorder` is set to the current byte order at the end of input data.

  Si byteorder es `NULL`, el códec se inicia en modo de orden nativo.

  Retorna `NULL` si el códec provocó una excepción.

PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI.

  Si consumed es `NULL`, se comporta como `PyUnicode_DecodeUTF16()`. Si consumed no es `NULL`, `PyUnicode_DecodeUTF16Stateful()` no tratará las secuencias de bytes UTF-16 incompletas finales (como un número impar de bytes o un par sustituto dividido) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará en consumed.

PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Retorna una cadena de bytes de Python usando la codificación UTF-16 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs UTF-7

Estas son las APIs del códec UTF-7:

PyObject *PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the UTF-7 encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI.

  Si consumed es `NULL`, se comporta como `PyUnicode_DecodeUTF7()`. Si consumed no es `NULL`, las secciones UTF-7 base-64 incompletas no se tratarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará en consumed.

### Códecs Unicode escapado

Estas son las APIs de códecs para Unicode escapado:

PyObject *PyUnicode_DecodeUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the Unicode-Escape encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando Unicode escapado (Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs para Unicode escapado en bruto

Estas son las API del códec Unicode escapado en bruto (Raw Unicode Escape):

PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the Raw-Unicode-Escape encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando Unicode escapado en bruto (Raw-Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs Latin-1

Estas son las API del códec Latin-1: Latin-1 corresponde a los primeros 256 ordinales Unicode y solo estos son aceptados por los códecs durante la codificación.

PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the Latin-1 encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando Latin-1 y retorna el resultado como un objeto de bytes Python. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs ASCII

Estas son las API del códec ASCII. Solo se aceptan datos ASCII de 7 bits. Todos los demás códigos generan errores.

PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the ASCII encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando ASCII y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

### Códecs de mapa de caracteres

This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs included in the `encodings` package). The codec uses mappings to encode and decode characters. The mapping objects provided must support the `__getitem__()` mapping interface; dictionaries and sequences work well.

Estos son las API de códec de mapeo:

PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Create a Unicode object by decoding size bytes of the encoded string str using the given mapping object. Return `NULL` if an exception was raised by the codec.

  Si mapping es `NULL`, se aplicará la decodificación Latin-1. De lo contrario, mapping debe asignar bytes ordinales (enteros en el rango de 0 a 255) a cadenas de caracteres Unicode, enteros (que luego se interpretan como ordinales Unicode) o `None`. Los bytes de datos sin asignar - los que causan un `LookupError`, así como los que se asignan a `None`, `0xFFFE` o `'\ ufffe'`, se tratan como asignaciones indefinidas y causan un error.

PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
  Return value: New reference. Part of the Stable ABI.

  Codifica un objeto Unicode usando el objeto mapping dado y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

  El objeto mapping debe asignar enteros ordinales Unicode a objetos de bytes, enteros en el rango de 0 a 255 o `None`. Los ordinales de caracteres no asignados (los que causan un `LookupError`), así como los asignados a `Ninguno`, se tratan como «mapeo indefinido» y causan un error.

La siguiente API de códec es especial en que asigna Unicode a Unicode.

PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
  Return value: New reference. Part of the Stable ABI.

  Traduce una cadena de caracteres aplicando una tabla de mapeo y retornando el objeto Unicode resultante. Retorna `NULL` cuando el códec provocó una excepción.

  La tabla de mapeo debe mapear enteros ordinales Unicode a enteros ordinales Unicode o `None` (causando la eliminación del carácter).

  Mapping tables need only provide the `__getitem__()` interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a `LookupError`) are left untouched and are copied as-is.

  errors tiene el significado habitual para los códecs. Puede ser `NULL`, lo que indica que debe usar el manejo de errores predeterminado.

### Códecs MBCS para Windows

Estas son las API de códec MBCS. Actualmente solo están disponibles en Windows y utilizan los convertidores Win32 MBCS para implementar las conversiones. Tenga en cuenta que MBCS (o DBCS) es una clase de codificaciones, no solo una. La codificación de destino está definida por la configuración del usuario en la máquina que ejecuta el códec.

PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
  Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

  Create a Unicode object by decoding size bytes of the MBCS encoded string str. Return `NULL` if an exception was raised by the codec.

PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

  Si consumed es `NULL`, se comporta como `PyUnicode_DecodeMBCS()`. Si consumed no es `NULL`, `PyUnicode_DecodeMBCSStateful()` no decodificará el byte inicial y el número de bytes que se han decodificado se almacenará en consumed.

PyObject *PyUnicode_DecodeCodePageStateful(int code_page, const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
  Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

  Similar to `PyUnicode_DecodeMBCSStateful()`, except uses the code page specified by code_page.

PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
  Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

  Codifica un objeto Unicode usando MBCS y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna `NULL` si el códec provocó una excepción.

PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
  Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

  Encode the Unicode object using the specified code page and return a Python bytes object. Return `NULL` if an exception was raised by the codec. Use `CP_ACP` code page to get the MBCS encoder.

  Added in version 3.3.

## Métodos y funciones de ranura (Slot)

Las siguientes API son capaces de manejar objetos Unicode y cadenas de caracteres en la entrada (nos referimos a ellos como cadenas de caracteres en las descripciones) y retorna objetos Unicode o enteros según corresponda.

Todos retornan `NULL` o `-1` si ocurre una excepción.

PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
  Return value: New reference. Part of the Stable ABI.

  Une dos cadenas de caracteres que dan una nueva cadena de caracteres Unicode.

PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
  Return value: New reference. Part of the Stable ABI.

  Divide una cadena de caracteres dando una lista de cadenas de caracteres Unicode. Si sep es `NULL`, la división se realizará en todas las subcadenas de espacios en blanco. De lo contrario, las divisiones ocurren en el separador dado. A lo sumo se realizarán maxsplit divisiones. Si es negativo, no se establece ningún límite. Los separadores no están incluidos en la lista resultante.

  On error, return `NULL` with an exception set.

  Equivalent to `str.split()`.

PyObject *PyUnicode_RSplit(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
  Return value: New reference. Part of the Stable ABI.

  Similar to `PyUnicode_Split()`, but splitting will be done beginning at the end of the string.

  On error, return `NULL` with an exception set.

  Equivalent to `str.rsplit()`.

PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
  Return value: New reference. Part of the Stable ABI.

  Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If keepends is `0`, the Line break characters are not included in the resulting strings.

PyObject *PyUnicode_Partition(PyObject *unicode, PyObject *sep)
  Return value: New reference. Part of the Stable ABI.

  Split a Unicode string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

  sep must not be empty.

  On error, return `NULL` with an exception set.

  Equivalent to `str.partition()`.

PyObject *PyUnicode_RPartition(PyObject *unicode, PyObject *sep)
  Return value: New reference. Part of the Stable ABI.

  Similar to `PyUnicode_Partition()`, but split a Unicode string at the last occurrence of sep. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

  sep must not be empty.

  On error, return `NULL` with an exception set.

  Equivalent to `str.rpartition()`.

PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
  Return value: New reference. Part of the Stable ABI.

  Une una secuencia de cadenas de caracteres usando el separator dado y retorna la cadena de caracteres Unicode resultante.

Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
  Part of the Stable ABI.

  Return `1` if substr matches `unicode[start:end]` at the given tail end (direction == `-1` means to do a prefix match, direction == `1` a suffix match), `0` otherwise. Return `-1` if an error occurred.

Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
  Part of the Stable ABI.

  Return the first position of substr in `unicode[start:end]` using the given direction (direction == `1` means to do a forward search, direction == `-1` a backward search). The return value is the index of the first match; a value of `-1` indicates that no match was found, and `-2` indicates that an error occurred and an exception has been set.

Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
  Part of the Stable ABI since version 3.7.

  Return the first position of the character ch in `unicode[start:end]` using the given direction (direction == `1` means to do a forward search, direction == `-1` a backward search). The return value is the index of the first match; a value of `-1` indicates that no match was found, and `-2` indicates that an error occurred and an exception has been set.

  Added in version 3.3.

  Distinto en la versión 3.7: start and end are now adjusted to behave like `unicode[start:end]`.

Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
  Part of the Stable ABI.

  Return the number of non-overlapping occurrences of substr in `unicode[start:end]`. Return `-1` if an error occurred.

PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
  Return value: New reference. Part of the Stable ABI.

  Replace at most maxcount occurrences of substr in unicode with replstr and return the resulting Unicode object. maxcount == `-1` means replace all occurrences.

int PyUnicode_Compare(PyObject *left, PyObject *right)
  Part of the Stable ABI.

  Compara dos cadenas de caracteres y retorna `-1`, `0`, `1` para menor que, igual y mayor que, respectivamente.

  Esta función retorna `-1` en caso de falla, por lo que se debe llamar a `PyErr_Occurred()` para verificar si hay errores.

  Ver también

  The `PyUnicode_Equal()` function.

int PyUnicode_Equal(PyObject *a, PyObject *b)
  Part of the Stable ABI since version 3.14.

  Test if two strings are equal:

  - Return `1` if a is equal to b.

  - Return `0` if a is not equal to b.

  - Set a `TypeError` exception and return `-1` if a or b is not a `str` object.

  The function always succeeds if a and b are `str` objects.

  The function works for `str` subclasses, but does not honor custom `__eq__()` method.

  Ver también

  The `PyUnicode_Compare()` function.

  Added in version 3.14.

int PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *string, Py_ssize_t size)
  Part of the Stable ABI since version 3.13.

  Compare a Unicode object with a char buffer which is interpreted as being UTF-8 or ASCII encoded and return true (`1`) if they are equal, or false (`0`) otherwise. If the Unicode object contains surrogate code points (`U+D800` - `U+DFFF`) or the C string is not valid UTF-8, false (`0`) is returned.

  Esta función no lanza excepciones.

  Added in version 3.13.

int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)
  Part of the Stable ABI since version 3.13.

  Similar to `PyUnicode_EqualToUTF8AndSize()`, but compute string length using `strlen()`. If the Unicode object contains null characters, false (`0`) is returned.

  Added in version 3.13.

int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
  Part of the Stable ABI.

  Compare a Unicode object, unicode, with string and return `-1`, `0`, `1` for less than, equal, and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input string as ISO-8859-1 if it contains non-ASCII characters.

  Esta función no lanza excepciones.

PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
  Return value: New reference. Part of the Stable ABI.

  Comparación enriquecida de dos cadenas de caracteres Unicode y retorna uno de los siguientes:

  - `NULL` en caso de que se produzca una excepción

  - `Py_True` or `Py_False` for successful comparisons

  - `Py_NotImplemented` in case the type combination is unknown

  Possible values for op are `Py_GT`, `Py_GE`, `Py_EQ`, `Py_NE`, `Py_LT`, and `Py_LE`.

PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
  Return value: New reference. Part of the Stable ABI.

  Retorna un nuevo objeto de cadena de caracteres desde format y args; esto es análogo al `format % args`.

int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
  Part of the Stable ABI.

  Check whether substr is contained in unicode and return true or false accordingly.

  substr has to coerce to a one element Unicode string. `-1` is returned if there was an error.

void PyUnicode_InternInPlace(PyObject **p_unicode)
  Part of the Stable ABI.

  Intern the argument *p_unicode in place. The argument must be the address of a pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as *p_unicode, it sets *p_unicode to it (releasing the reference to the old string object and creating a new strong reference to the interned string object), otherwise it leaves *p_unicode alone and interns it.

  (Clarification: even though there is a lot of talk about references, think of this function as reference-neutral. You must own the object you pass in; after the call you no longer own the passed-in reference, but you newly own the result.)

  This function never raises an exception. On error, it leaves its argument unchanged without interning it.

  Instances of subclasses of `str` may not be interned, that is, PyUnicode_CheckExact(*p_unicode) must be true. If it is not, then – as with any other error – the argument is left unchanged.

  Note that interned strings are not “immortal”. You must keep a reference to the result to benefit from interning.

PyObject *PyUnicode_InternFromString(const char *str)
  Return value: New reference. Part of the Stable ABI.

  A combination of `PyUnicode_FromString()` and `PyUnicode_InternInPlace()`, meant for statically allocated strings.

  Return a new («owned») reference to either a new Unicode string object that has been interned, or an earlier interned string object with the same value.

  Python may keep a reference to the result, or make it immortal, preventing it from being garbage-collected promptly. For interning an unbounded number of different strings, such as ones coming from user input, prefer calling `PyUnicode_FromString()` and `PyUnicode_InternInPlace()` directly.

unsigned int PyUnicode_CHECK_INTERNED(PyObject *str)

  Return a non-zero value if str is interned, zero if not. The str argument must be a string; this is not checked. This function always succeeds.

  Detalles de implementación de CPython: A non-zero return value may carry additional information about how the string is interned. The meaning of such non-zero values, as well as each specific string’s intern-related details, may change between CPython versions.

## PyUnicodeWriter

The `PyUnicodeWriter` API can be used to create a Python `str` object.

Added in version 3.14.

type PyUnicodeWriter

  A Unicode writer instance.

  The instance must be destroyed by `PyUnicodeWriter_Finish()` on success, or `PyUnicodeWriter_Discard()` on error.

PyUnicodeWriter *PyUnicodeWriter_Create(Py_ssize_t length)

  Create a Unicode writer instance.

  length must be greater than or equal to `0`.

  If length is greater than `0`, preallocate an internal buffer of length characters.

  Set an exception and return `NULL` on error.

PyObject *PyUnicodeWriter_Finish(PyUnicodeWriter *writer)

  Return the final Python `str` object and destroy the writer instance.

  Set an exception and return `NULL` on error.

  The writer instance is invalid after this call.

void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)

  Discard the internal Unicode buffer and destroy the writer instance.

  If writer is `NULL`, no operation is performed.

  The writer instance is invalid after this call.

int PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)

  Write the single Unicode character ch into writer.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, const char *str, Py_ssize_t size)

  Decode the string str from UTF-8 in strict mode and write the output into writer.

  size is the string length in bytes. If size is equal to `-1`, call `strlen(str)` to get the string length.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

  See also `PyUnicodeWriter_DecodeUTF8Stateful()`.

int PyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer, const char *str, Py_ssize_t size)

  Write the ASCII string str into writer.

  size is the string length in bytes. If size is equal to `-1`, call `strlen(str)` to get the string length.

  str must only contain ASCII characters. The behavior is undefined if str contains non-ASCII characters.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

  Added in version 3.14.

int PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, const wchar_t *str, Py_ssize_t size)

  Write the wide string str into writer.

  size is a number of wide characters. If size is equal to `-1`, call `wcslen(str)` to get the string length.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *writer, Py_UCS4 *str, Py_ssize_t size)

  Writer the UCS4 string str into writer.

  size is a number of UCS4 characters.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj)

  Call `PyObject_Str()` on obj and write the output into writer.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj)

  Call `PyObject_Repr()` on obj and write the output into writer.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str, Py_ssize_t start, Py_ssize_t end)

  Write the substring `str[start:end]` into writer.

  str must be Python `str` object. start must be greater than or equal to 0, and less than or equal to end. end must be less than or equal to str length.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)

  Similar to `PyUnicode_FromFormat()`, but write the output directly into writer.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

int PyUnicodeWriter_DecodeUTF8Stateful(PyUnicodeWriter *writer, const char *string, Py_ssize_t length, const char *errors, Py_ssize_t *consumed)

  Decode the string str from UTF-8 with errors error handler and write the output into writer.

  size is the string length in bytes. If size is equal to `-1`, call `strlen(str)` to get the string length.

  errors is an error handler name, such as `"replace"`. If errors is `NULL`, use the strict error handler.

  If consumed is not `NULL`, set *consumed to the number of decoded bytes on success. If consumed is `NULL`, treat trailing incomplete UTF-8 byte sequences as an error.

  On success, return `0`. On error, set an exception, leave the writer unchanged, and return `-1`.

  See also `PyUnicodeWriter_WriteUTF8()`.

## Deprecated API

The following API is deprecated.

type Py_UNICODE

  This is a typedef of `wchar_t`, which is a 16-bit type or 32-bit type depending on the platform. Please use `wchar_t` directly instead.

  Distinto en la versión 3.3: En versiones anteriores, este era un tipo de 16 bits o de 32 bits, dependiendo de si seleccionó una versión Unicode «estrecha» o «amplia» de Python en el momento de la compilación.

  Deprecated since version 3.13, removed in version 3.15.

int PyUnicode_READY(PyObject *unicode)

  Do nothing and return `0`. This API is kept only for backward compatibility, but there are no plans to remove it.

  Added in version 3.3.

  Obsoleto desde la versión 3.10: This API does nothing since Python 3.12. Previously, this needed to be called for each string created using the old API (`PyUnicode_FromUnicode()` or similar).

unsigned int PyUnicode_IS_READY(PyObject *unicode)

  Do nothing and return `1`. This API is kept only for backward compatibility, but there are no plans to remove it.

  Added in version 3.3.

  Obsoleto desde la versión 3.14: This API does nothing since Python 3.12. Previously, this could be called to check if `PyUnicode_READY()` is necessary.