English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Antes de aprender sobre conversión de tipos en Python, debes entender Tipos de datos de Python.
El proceso de convertir el valor de un tipo de datos (enteros, cadenas, flotantes, etc.) a otro tipo de datos se llama conversión de tipos. Python tiene dos tipos de conversión de tipos.
Conversión implícita de tipos
Conversión explícita de tipo
En la conversión implícita de tipos, Python convierte automáticamente un tipo de datos en otro sin la participación del usuario.
Veamos un ejemplo en el que Python promueve la conversión de tipos de datos más bajos (enteros) a tipos de datos más altos (flotantes) para evitar la pérdida de datos.
num_int = 123 num_flo = 1.23 num_new = num_int + num_flo print("The data type of num_int:",type(num_int)) print("El tipo de datos de num_flo:", type(num_flo)) print("El valor de num_new:", num_new) print("El tipo de datos de num_new:", type(num_new))
When we run the above program, the output will be:
The data type of num_int: <class 'int'> El tipo de datos de num_flo: <class 'float'> El valor de num_new: 124.23 El tipo de datos de num_new: <class 'float'>
in the above program
Vamos a sumar dos variablesnum_intandsumar num_floy almacenaremos el valor en la variableen num_new.
veremos los tipos de datos de todos los tres objetos.
En la salida, podemos vernum_intsu tipo de datos es integer,num_flosu tipo de datos es float.
Además, podemos vernum_newcon el tipo de datos float, porque Python siempre convierte el tipo de datos más pequeño al tipo de datos más grande para evitar la pérdida de datos.
Ahora, intentemos sumar una cadena y un entero y ver cómo maneja Python esto.
num_int = 123 num_str = "456" print("The data type of num_int:",type(num_int)) print("El tipo de datos de num_str:", type(num_str)) print(num_int+num_str)
When we run the above program, the output will be:
The data type of num_int: <class 'int'> El tipo de datos de num_str: <class 'str'> Traceback (llamada más reciente última): Archivo "python", línea 7, en <module> TypeError: tipo de operando no soportado para +: 'int' y 'str'
in the above program
tenemos dos variablesnum_int ynum_strsumar.
Como se puede ver en la salida, obtenemos TypeError. En este caso, Python no puede usar la conversión implícita.
Sin embargo, Python ofrece una solución para este tipo de situación, denominada "Conversión explícita".
en "Conversión explícita de tipoen el que el usuario convierte el tipo de datos del objeto al tipo de datos deseado. Usamos conversiones de tipo explícitas como las funciones predefinidas int(), float(), str() y otras.
Este tipo de conversión también se llama conversión de tipo, porque el usuario fuerza la conversión (cambio) del tipo de datos del objeto.
Gramática :
<required_datatype>(expression)
Type conversion can be completed by assigning the required data type function to the expression.
num_int = 123 num_str = "456" print("The data type of num_int:",type(num_int)) print("The data type of num_str before type conversion:",type(num_str)) num_str = int(num_str) print("The data type of num_str after type conversion:",type(num_str)) num_sum = num_int + num_str print("sum of num_int and num_str:",num_sum) print("sum data type:",type(num_sum))
When we run the above program, the output will be:
The data type of num_int: <class 'int'> The data type of num_str before type conversion: <class 'str'> The data type of num_str after type conversion: <class 'int'> sum of num_int and num_str: 579 sum data type: <class 'int'>
in the above program
Wenum_strandnum_intadd variables.
We use the int() function tonum_strfrom string (high) to integer (low) type to perform addition.
Convertnum_strAfter converting to an integer, Python can add these two variables.
Finally, we getnum_sumValue and and the data type of the value are integers.
Type conversion is the conversion of an object from one data type to another.
Implicit type conversion is automatically executed by the Python interpreter.
Python avoids data loss in implicit type conversion.
Explicit type conversion, also known as type casting, is when the user uses predefined functions to convert the data type of an object.
In type conversion, data loss may occur when we force an object to a specific data type.