Computer >> Computer tutorials >  >> Programming >> Python

Valid Number in Python


Suppose we have a strings, we have to check whether that string is representing a number or not. So if the strings are like “0.2”, “abc”, “hello”, “-2.5”, “10”, then the answers will be true, false, false, true, true respectively.

To solve this, we will follow these steps −

  • To solve this we will use the string parsing technique of our programming language. We will try to convert string to a number, if there is no exception, then that will be a number, otherwise not a number.

Example

Let us see the following implementation to get a better understanding −

class Solution(object):
   def isNumber(self, s):
      s = s.strip()
      try:
         s = float(s)
         return True
      except:
         return False

ob = Solution()
print(ob.isNumber("0.2"))
print(ob.isNumber("abc"))
print(ob.isNumber("Hello"))
print(ob.isNumber("-2.5"))
print(ob.isNumber("10"))

Input

“0.2”
“abc”
“Hello”
“-2.5”
“10”

Output

True
False
False
True
True