- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a given string is a valid number in Python
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 −
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
Advertisements