+ 3
How to check if a string is float in python? Without using try:
11 Réponses
+ 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. 😉
+ 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
+ 4
How about a regular expression?
+ 1
Hi. You could try
if float(string) == string:
+ 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
+ 1
How to listen voice of my computer by using python
0
Is this what you meant?
https://code.sololearn.com/cBqcdw0yKI3z/?ref=app