Pour convertir une chaîne de caractères en float sous python on peut utiliser la fonction "built-in" intitulée float(), exemple:
>>> s = '3.1415'>>> type(s)<class 'str'>>>> s = float(s)>>> type(s)<class 'float'>
Cependant si la chaîne de caractères ne peut pas être convertie en float on va obtenir le message d'erreur suivant
ValueError: could not convert string to float:
pour éviter cela on peut procéder comme suit:
>>> try:... float(s)... print('True')... except:... print('False')...3.1415True
ou créer une fonction:
>>> def check_string_to_float(s):... try:... float(s)... print('True')... except:... print('False')
exemple:
>>> s = '3.1415...'>>> check_string_to_float(s)False
Note: si la chaîne de caractères utilise des virgules au lieu de points, on peut utiliser la fonction replace():
>>> s = '3,1415'>>> check_string_to_float(s)False>>> check_string_to_float(s.replace(',','.'))True
Autre exemple:
>>> s = 'abcd'>>> check_string_to_float(s)False
Références
| Liens | Site |
|---|---|
| float() | python doc |
| Fast checking if a string can be converted to float or int in python | stackoverflow |
| Checking if a string can be converted to float in Python | stackoverflow |
| Python parse comma-separated number into int | stackoverflow |
