How can I tell when a string is in fact a number?
Alex Martelli
aleaxit at yahoo.com
Tue Nov 7 10:40:17 EST 2000
"Joshua Muskovitz" <josh at open.com> wrote in message
news:3a0707bc_3 at corp.newsfeeds.com...
> Thanks for all the timing benchmarks. This is effectively the only
response
> I've seen to my "why bother with re at all?" question, when I posted a
much
> more readable solution which only used filter and lambda. Also, thanks
for
I guess it's an issue of "readable to WHO?"-).
re.match(r'[0-9]*$', str)
or the equivalent
re.match(r'\d*$', str)
are quite readable if one understands even the basics of RE -- any
old-time user of VI, for example (but most good/powerful editors
today give you a modicum of RE's -- hey, even Microsoft Visual Studio
on Windows does!-).
OTOH, lambda and reduce (there was no use of filter in the solution
you had posted) are somewhat more mysterious to many users - even
the fact that, say:
x and y in string.digits
parses as
x and (y in string.digits)
and not as
(x and y) in string.digits
may cause head-scratching in some quarters:-).
Btw, I don't think there _was_ any presented solution using
filter, though it IS in fact a pretty natural approach...:
def isanum(str):
return not filter(lambda x: not x in string.digits, str)
> summarizing all of the intersting ways of solving this. The map solution
> never would have occurred to me. Python just gets better and better!
You're welcome!-) Although some would object to characterizing
the fact that "there's more than one way to do it" as a good
thing (there's another scripting-language-starting-with-P that
seems to have cornered _that_ niche of the market, I guess:-).
Alex
More information about the Python-list
mailing list