Python Program to Check if a String Is a Number
Beginner · Strings
Anything typed by a user arrives as a string, even when it looks like a number, so programs often need to check whether "42" or "3.14" can be turned into a number before doing maths with it. This program tries the conversion and catches the error when it fails.
Program
"2026" is a number | isdigit(): True "-15" is a number | isdigit(): False "3.14" is a number | isdigit(): False "12abc" is not a number | isdigit(): False "1e3" is a number | isdigit(): False " 42 " is a number | isdigit(): False "" is not a number | isdigit(): False
How it works
float(text)converts the string to a number when it can, and raises aValueErrorwhen it cannot.tryandexcept ValueErrorcatch that error, so a bad value gives a message instead of stopping the program.float()accepts signs, decimal points, spaces around the number and forms like"1e3"(1000), which makes it a better test thanisdigit().isdigit()isTrueonly when every character is a digit, so it says no to "-15" and "3.14"; use it only for whole numbers without a sign.float()also accepts the words "nan" and "inf", which stand for "not a number" and infinity, so reject those yourself if they matter.
Other ways to write it
Whole numbers only, with int()
42 -> whole number -7 -> whole number 3.5 -> not a whole number seven -> not a whole number
int() accepts a sign but refuses a decimal point, so it is the right test when only whole numbers make sense, like an age or a roll number.
Checking by hand, without try
12 -> number -3.75 -> number 4.2.1 -> not a number .5 -> number abc -> not a number - -> not a number
The function allows one sign and at most one decimal point, then insists that everything left is digits. It is a good exercise in string methods, but it does not accept forms like 1e3.
Try it yourself
Add "1,000" and "nan" to the list and explain the result for each.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Extract Numbers from a String
- Count Letters, Digits and Spaces in a String
- Check if a Character Is a Letter, Digit or Symbol
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises