Conversión y formato de cadenas de caracteres¶
Funciones para conversión de números y salida de cadena de caracteres formateadas.
-
int
PyOS_snprintf(char *str, size_t size, const char *format, ...)¶ Output not more than size bytes to str according to the format string format and the extra arguments. See the Unix man page snprintf(3).
-
int
PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)¶ Output not more than size bytes to str according to the format string format and the variable argument list va. Unix man page vsnprintf(3).
PyOS_snprintf() and PyOS_vsnprintf() wrap the Standard C library
functions snprintf() and vsnprintf(). Their purpose is to
guarantee consistent behavior in corner cases, which the Standard C functions do
not.
The wrappers ensure that str[size-1] is always '\0' upon return. They
never write more than size bytes (including the trailing '\0') into str.
Both functions require that str != NULL, size > 0 and format !=
NULL.
Si la plataforma no tiene vsnprintf() y el tamaño del búfer necesario para evitar el truncamiento excede size en más de 512 bytes, Python aborta con a Py_FatalError().
El valor de retorno (rv) para estas funciones debe interpretarse de la siguiente manera:
When
0 <= rv < size, the output conversion was successful and rv characters were written to str (excluding the trailing'\0'byte atstr[rv]).When
rv >= size, the output conversion was truncated and a buffer withrv + 1bytes would have been needed to succeed.str[size-1]is'\0'in this case.When
rv < 0, «something bad happened.»str[size-1]is'\0'in this case too, but the rest of str is undefined. The exact cause of the error depends on the underlying platform.
Las siguientes funciones proporcionan cadenas de caracteres independientes de la configuración regional para numerar las conversiones.
-
double
PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)¶ Convierte una cadena de caracteres
sen undouble, generando una excepción de Python en caso de falla. El conjunto de cadenas de caracteres aceptadas corresponde al conjunto de cadenas aceptadas por el constructor de Pythonfloat(), excepto quesno debe tener espacios en blanco iniciales o finales. La conversión es independiente de la configuración regional actual.Si
endptresNULL, convierte toda la cadena de caracteres. LanzaValueErrory retorna-1.0si la cadena de caracteres no es una representación válida de un número de punto flotante.If endptr is not
NULL, convert as much of the string as possible and set*endptrto point to the first unconverted character. If no initial segment of the string is the valid representation of a floating-point number, set*endptrto point to the beginning of the string, raise ValueError, and return-1.0.Si
srepresenta un valor que es demasiado grande para almacenar en un flotante (por ejemplo,"1e500"es una cadena de caracteres de este tipo en muchas plataformas), entonces sioverflow_exceptionesNULLretornaPy_HUGE_VAL(con un signo apropiado) y no establece ninguna excepción. De lo contrario,overflow_exceptiondebe apuntar a un objeto excepción de Python; lanza esa excepción y retorna-1.0. En ambos casos, configura*endptrpara que apunte al primer carácter después del valor convertido.Si se produce algún otro error durante la conversión (por ejemplo, un error de falta de memoria), establece la excepción Python adecuada y retorna
-1.0.Nuevo en la versión 3.1.
-
char*
PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)¶ Convierte un
doubleval en una cadena de caracteres usando format_code, precision y flags suministrados.format_code debe ser uno de
'e','E','f','F','g','G'or'r'. Para'r', la precision suministrada debe ser 0 y se ignora. El código de formato'r'especifica el formato estándarrepr().flags can be zero or more of the values
Py_DTSF_SIGN,Py_DTSF_ADD_DOT_0, orPy_DTSF_ALT, or-ed together:Py_DTSF_SIGNsignifica preceder siempre a la cadena de caracteres retornada con un carácter de signo, incluso si val no es negativo.Py_DTSF_ADD_DOT_0significa asegurarse de que la cadena de caracteres retornada no se verá como un número entero.Py_DTSF_ALTsignifica aplicar reglas de formato «alternativas». Consulte la documentación del especificadorPyOS_snprintf`()“#”` para obtener más detalles.
Si ptype no es
NULL, el valor al que apunta se establecerá en uno dePy_DTST_FINITE,Py_DTST_INFINITEoPy_DTST_NAN, lo que significa que val es un número finito, un número infinito o no es un número, respectivamente.El valor de retorno es un puntero a buffer con la cadena de caracteres convertida o
NULLsi la conversión falla. La persona que llama es responsable de liberar la cadena de caracteres retornada llamando aPyMem_Free().Nuevo en la versión 3.1.
-
int
PyOS_stricmp(const char *s1, const char *s2)¶ Case insensitive comparison of strings. The function works almost identically to
strcmp()except that it ignores the case.
-
int
PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)¶ Case insensitive comparison of strings. The function works almost identically to
strncmp()except that it ignores the case.