# How can I tell when a string is in fact a number?

Alex Martelli aleaxit at yahoo.com
Mon Nov 6 11:58:55 CET 2000

```"Joshua Muskovitz" <josh at open.com> wrote in message
news:3a05f10d_3 at corp.newsfeeds.com...
> Why use re at all?

Because it's a simpler solution to a specific problem...?-)

(ignore the fact that I perpetrated a silly typo in my
original re suggestion... it's still the simplest one!-)

> def isanum(str):
>     import string
>     return reduce(lambda x, y: x and y in string.digits, str, str != "")
>
> >>> isanum("")
> 0
> >>> isanum("1234")
> 1
> >>> isanum("123xxx566")
> 0
> >>> isanum("123.45")
> 0
>
> This correctly handles the original problem of ensuring that the input
> string contains *only* digits.  Of course, the original problem also

Note the subject line -- it's asking whether a string "is in fact
a number", NOT the different question of whether "it contains only
digits" (although that is the problem the original _code_ seems to
be addressing).  I focused on 'contain-only-digits' too, as you
did, but that's just because it's a more amusing problem:-)

> returned 1 for the empty input string ("").  To handle this, replace [str
!=
> ""] with [1] in the reduce function.
>
>
why-does-everyone-always-try-to-present-a-solution-to-something-other-than-t
> he-original-problem'ly yrs,

It's far from clear what "the original problem" was in this case,
given the slight contradiction between the 'specification' (subject)
and the test of the original post.

Here's another whimsical solution (to the digits-only problem),
with _peculiar_ failings...

def isanum(str):
l=list(str)
l.sort()
return l[0]>='0' and l[-1]<='9'

Apart from little defects such as being O(N log N), and breaking
for the empty-string, I wonder if there's any Python implementation
where this will really fall apart (EBCDIC...?).

Alex

```