How to check if string input is a number?
How do I check if a user's string input is a number (e.g. -1
, 0
, 1
, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
The above won't work since input
always returns a string.
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
See Handling Exceptions https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
The method isnumeric()
will do the job (Documentation for python3.x):
>>>a = '123'
>>>a.isnumeric()
True
But remember:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric()
returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
EDITED: You could also use this below code to find out if its a number or also a negative
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.