Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string input is a number?

People also ask

How do you check if a string input is a number?

Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work.

How do you check if a value is a string or number in Python?

You Can Type: user_input = input("Enter something: ") if type(user_input) == int: print(user_input, "Is a number") else: print("Not a number") try: val = int(user_input) except ValueError: print("That's not an int!")

How do you check if a string is a number JS?

Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.

How do you check if a string is a number in C?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.


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.