We have string.isdigit(), why not string.isNumber()?

We have string.isdigit(), why not string.isNumber()?

Post by MooMaste » Fri, 02 May 2008 09:56:06


N00b question alert! I did a search for isdigit() in the group
discussion, and it didn't look like the question had been asked in the
first 2 pages, so sorry if it was...

The manual documentation says:
"isdigit( )

Return true if all characters in the string are digits and there is at
least one character, false otherwise.
For 8-bit strings, this method is locale-dependent. "

So it makes sense that something like 5.6 would return false. But what
if we want to make sure that our string is a valid number, ie decimals
included?

I know how to write a regexp or method or whatever to do this, my main
question is *why* something like an isNumber() method is not baked
into the class. Does such functionality exist somewhere else in the
standard library that I'm just missing?
 
 
 

We have string.isdigit(), why not string.isNumber()?

Post by Roy Smit » Fri, 02 May 2008 10:03:45

In article
< XXXX@XXXXX.COM >,



Just call int(x) or float(x) inside a try block and see if if it raises an
exception.

 
 
 

We have string.isdigit(), why not string.isNumber()?

Post by Dan Bisho » Fri, 02 May 2008 10:04:20


A string s is a valid number if float(s) does not raise a ValueError.
 
 
 

We have string.isdigit(), why not string.isNumber()?

Post by Ben Finne » Fri, 02 May 2008 11:25:01

MooMaster < XXXX@XXXXX.COM > writes:


Because that name wouldn't conform to PEP 8.

(Also, and more importantly, because it's more correct to use it as
input to creating a new object of the type you want, and catch the
exception if it fails.)

--
\ "Courage is resistance to fear, mastery of fear not absence |
`\ of fear." ark Twain, _Pudd'n'head Wilson_ |
_o__) |
Ben Finney