It would be nice to have a string method that checks for a float. Currently
there is no support for this, either built-in or in the standard library. There
is a thread, dating back to Dec 2020, that proposes a trivial implementation
for str.isfloat . I was thinking of a method that did more.
Consider the following code. It returns True if the string is a proper float,
False if it is an int and None otherwise.
def isfloat(s):
try:
int(s)
return False
except ValueError:
try:
float(s)
return True
except ValueError:
return None
This will be useful when we want to preserve the type of the number that is in
string format. Anywhere a number is input as a string to a method and we want
to later on output the original number, we can use the above. If, instead (as
suggested in the other thread), the string is simply converted to a float, then
the info that the string was an int is lost.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/D5U6MTIXMBR6BZRVMCLZAXSICWZ4VOWT/
Code of Conduct: http://python.org/psf/codeofconduct/