CKTIS / Python
Conversione dei tipi
Un costruttore di tipo converte un valore secondo le sue regole e solleva un’eccezione per un ingresso non supportato.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
quantity = int(text, 10)
whole = int(number)Un costruttore di tipo converte un valore secondo le sue regole e solleva un’eccezione per un ingresso non supportato.
int interpreta testo intero nella base indicata e tronca un valore in virgola mobile verso zero. Un testo con punto decimale non rappresenta un intero per int. bool verifica la verità, quindi la stringa non vuota 'False' è vera.
I risultati sono 17, ValueError, -2 e TypeError per None.
assert int('ff',16)==255 and int(-2.8)==-2
assert int('010')==10
try: int('010',0)
except ValueError: pass
else: raise AssertionError
assert bool('False') and not bool('')
Esempi
for value in (" 017 ", "-2.8", -2.8, None):
try:
print(int(value))
except (ValueError, TypeError) as error:
print(type(error).__name__)
Risultato
17 ValueError -2 TypeError
I risultati sono 17, ValueError, -2 e TypeError per None.