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

Fredrik Lundh fredrik at effbot.org
Sun Nov 5 17:48:05 EST 2000


Alex Martelli wrote:
> The simplest way to check if a string is made up
> just of digits is probably via the re module...:
>
> def isanum(str):
>     import re
>     return re.match(r'\d*',str)!=None
>
> this checks for '0 or more digits', like your original
> code -- i.e., an empty str will get a 1 return value.

and so will anything else that starts with zero
or more digits:

>>> print isanum("")
1
>>> print isanum("1")
1
>>> print isanum("this is not a number")
1

</F>





More information about the Python-list mailing list