# Valid Number in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 −

Live Demo

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
Updated on 26-May-2020 12:10:37