Check if a given string is a valid number in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string, that holds numeric characters and decimal points, we have to check whether that string is representing a number or not. If the input is like “2.5”, output will be true, if the input is “xyz”, output will be false.

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 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 better understanding −

 Live Demo

def isNumeric(s):
   s = s.strip()
   try:
      s = float(s)
      return True
   except:
      return False
print(isNumeric("0.2"))
print(isNumeric("xyz"))
print(isNumeric("Hello"))
print(isNumeric("-2.5"))
print(isNumeric("10"))

Input

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

Output

True
False
False
True
True
raja
Published on 27-Aug-2020 16:50:44
Advertisements