On Fri, Oct 01, 2021 at 08:56:39AM -0000, [email protected] wrote:
> 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.
Given the design you gave for this function, how would you use it?
s = input("Enter a number: ") # Or some other string
three_way_flag = isfloat(s) # Or s.isfloat()
if three_way_flag is None:
raise ValueError("Not a number!")
elif three_way_flag:
num = int(s)
else:
num = float(s)
Or did I get the true/false flags the wrong way around. I forget.
Seems unnecessarily awkward and inefficient. Why not just have a
function which takes a string and returns either an int or a float,
whichever is appropriate?
That function is pretty easy to write. And as Dennis mentions, there are
many possible variations. What if you want a Decimal or a Fraction,
or a complex number? What if you want to return a NAN instead of raising
an exception?
I'm also unsure when I might care about preserving the type of the
number in this way. Typically I'm expecting to work with either floats
or ints. If I'm working with ints, then a float would be an error, and I
should just call `int(s)` and if the string contains a decimal point,
that will be an error. If I'm working with floats, then just calling
`float(s)` will have exactly the same effect as calling `int(s)` and
then doing float arithmetic on it.
Well, not *quite* exactly.
s = '1234567890'*100
x = float(s)*1.0
y = int(s)*1.0
Calculating x will give the float INF; calculating y will raise
OverflowError.
So I think that this sort of function to preserve the type of the
numeric string is going to have a very limited use.
--
Steve
_______________________________________________
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/HSUFQJ2BREL2ON43UKIHDUC6INCBNEPC/
Code of Conduct: http://python.org/psf/codeofconduct/