Editor

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

check_if_number_string.py
samples = ["2026", "-15", "3.14", "12abc", "1e3", " 42 ", ""]
# or: samples = [input("Enter something: ")]
for text in samples:
try:
float(text) # works for whole numbers, decimals and signs
result = "is a number"
except ValueError:
result = "is not a number"
print(f'"{text}"', result, "| isdigit():", text.isdigit())
Output
"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

  1. float(text) converts the string to a number when it can, and raises a ValueError when it cannot.
  2. try and except ValueError catch that error, so a bad value gives a message instead of stopping the program.
  3. float() accepts signs, decimal points, spaces around the number and forms like "1e3" (1000), which makes it a better test than isdigit().
  4. isdigit() is True only when every character is a digit, so it says no to "-15" and "3.14"; use it only for whole numbers without a sign.
  5. 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()

Whole numbers only, with int()
def is_whole_number(text):
try:
int(text)
return True
except ValueError:
return False
for text in ["42", "-7", "3.5", "seven"]:
print(text, "->", "whole number" if is_whole_number(text) else "not a whole number")
Output
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

Checking by hand, without try
def looks_like_decimal(text):
if text and text[0] in "+-":
text = text[1:] # allow one sign at the start
if text.count(".") > 1:
return False
digits = text.replace(".", "")
return digits.isdigit()
for text in ["12", "-3.75", "4.2.1", ".5", "abc", "-"]:
print(text, "->", "number" if looks_like_decimal(text) else "not a number")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises