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:

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.

Nuevo en la versión 3.3.

type Py_UNICODE

This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.

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.

Obsoleto desde la versión 3.13, se eliminará en la versión 3.15.

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.

Nuevo en la versión 3.3.

PyTypeObject PyUnicode_Type
Part of the Stable ABI.

Esta instancia de PyTypeObject representa el tipo Python Unicode. Está expuesto al código de Python como str.

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.

int PyUnicode_READY(PyObject *unicode)

Returns 0. This API is kept only for backward compatibility.

Nuevo en la versión 3.3.

Obsoleto desde la versión 3.10: This API does nothing since Python 3.12.

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).

Nuevo en la versión 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.

Nuevo en la versión 3.3.

PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND

Retorna los valores de la macro PyUnicode_KIND().

Nuevo en la versión 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).

Nuevo en la versión 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).

Nuevo en la versión 3.3.

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

Write into a canonical representation data (as obtained with PyUnicode_DATA()). This function performs no sanity checks, and is intended for usage in loops. The caller should cache the kind value and data pointer as obtained from other calls. index is the index in the string (starts at 0) and value is the new code point value which should be written to that location.

Nuevo en la versión 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.

Nuevo en la versión 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.

Nuevo en la versión 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.

Nuevo en la versión 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 Identificadores y palabras clave. 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.

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)

Retorna 1 o 0 dependiendo de si ch es un carácter imprimible. Los caracteres no imprimibles son aquellos definidos en la base de datos de caracteres Unicode como «Otro» o «Separador», excepto el espacio ASCII (0x20) que se considera imprimible. (Tenga en cuenta que los caracteres imprimibles en este contexto son aquellos a los que no se debe escapar cuando repr() se invoca en una cadena de caracteres. No tiene relación con el manejo de cadenas de caracteres escritas en sys.stdout o sys.stderr.)

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 characters 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.

Esta es la forma recomendada de asignar un nuevo objeto Unicode. Los objetos creados con esta función no se pueden redimensionar.

Nuevo en la versión 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).

Nuevo en la versión 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_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.

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.

Nuevo en la versión 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.

Nuevo en la versión 3.3.

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.

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

Nuevo en la versión 3.3.

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

Escribe un carácter en una cadena de caracteres. La cadena debe haberse creado a través de PyUnicode_New(). Dado que se supone que las cadenas de caracteres Unicode son inmutables, la cadena no debe compartirse o no se ha cifrado todavía.

Esta función comprueba que unicode es un objeto Unicode, que el índice no está fuera de los límites y que el objeto se puede modificar de forma segura (es decir, si su número de referencia es uno).

Nuevo en la versión 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.

Nuevo en la versión 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.

Nuevo en la versión 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.

Nuevo en la versión 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.

Nuevo en la versión 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().

Nuevo en la versión 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().

Nuevo en la versión 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().

Nuevo en la versión 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.

ParseTuple 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 a PyBytesObject* which must be released when it is no longer used.

Nuevo en la versión 3.1.

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

Para decodificar nombres de archivo a str durante el análisis de argumentos, se debe usar el convertidor "O&", pasando PyUnicode_FSDecoder() como la función de conversión:

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

ParseTuple 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 a PyUnicodeObject* which must be released when it is no longer used.

Nuevo en la versión 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().

Nuevo en la versión 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.

Nuevo en la versión 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

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.

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.

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.

Nuevo en la versión 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.

Nuevo en la versión 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_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.

Nuevo en la versión 3.3.

Métodos & Ranuras (Slots)

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.

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_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.

Nuevo en la versión 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.

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 characters or the C string is not valid UTF-8, false (0) is returned.

Esta función no lanza excepciones.

Nuevo en la versión 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.

Nuevo en la versión 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:

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 (creating a new strong reference). (Clarification: even though there is a lot of talk about references, think of this function as reference-neutral; you own the object after the call if and only if you owned it before the call.)

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

Una combinación de PyUnicode_FromString() y PyUnicode_InternInPlace(), que retorna un nuevo objeto de cadena de caracteres Unicode que ha sido creado internamente o una nueva referencia(«propia») a un objeto de cadena de caracteres interno anterior con el mismo valor.