+ 3

How to check if a string is float in python? Without using try:

19th Oct 2019, 12:46 PM
Abhishek Kumar
Abhishek Kumar - avatar
11 Respostas
+ 5
If you float the string 'abc', you'll get an error. To avoid that, you'd have to use try-except. But that is precisely what Abhishek Kumar doesn't want to do! try will probably be the shortest way, whatever you attempt. If you want to do it anyway, you'll have to check if the string completely looks like a float. Has it only numbers in it, but one and only one point? Is it maybe one of the abbreviated writings Python allows, like .4 or 9.? Is it an exponentially expressed float like 1.5e-7? So basically, is there maximally one e in it, and maximally one minus? It can be a capital E, too, so don't forget that. And everything needs to be in the right place. So either you strictly limit the way the user can input a float (even then you'll have a bit of testing)... ... or you just use try and except after all. 😉
19th Oct 2019, 1:24 PM
HonFu
HonFu - avatar
+ 5
isfloat = lambda x: 'float' in str(type(x)) Mirielle🐶 [Inactive] Edit: I misread the brief It asks to check if a string is a float
19th Oct 2019, 5:12 PM
Louis
Louis - avatar
+ 4
How about a regular expression?
19th Oct 2019, 2:30 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Hi. You could try if float(string) == string:
19th Oct 2019, 1:02 PM
Dmytro Novak
Dmytro Novak - avatar
+ 1
Jannik the code won't work for inputs which have more than 2 dots. Ex: 4.4.5, 8.........8......8 and it will also consider strings which have dot as float Ex: hi.,he...llo
20th Oct 2019, 7:04 PM
Abhishek Kumar
Abhishek Kumar - avatar
+ 1
How to listen voice of my computer by using python
21st Oct 2019, 2:17 AM
Nathan Wyane
Nathan Wyane - avatar
20th Oct 2019, 6:13 PM
Jannik Müller
Jannik Müller - avatar