How to check if string input is a number? [duplica

2018-12-31 03:46发布

This question already has an answer here:

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.

24条回答
若你有天会懂
2楼-- · 2018-12-31 04:44

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 
查看更多
墨雨无痕
3楼-- · 2018-12-31 04:45

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!")
查看更多
美炸的是我
4楼-- · 2018-12-31 04:46
while True:
    b1=input('Type a number:')
    try:
        a1=int(b1)
    except ValueError:
        print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})       
    else:
        print ('You typed "{}".'.format(a1))
        break

This makes a loop to check whether input is an integer or not, result would look like below:

>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>> 
查看更多
只靠听说
5楼-- · 2018-12-31 04:46

try this! it worked for me even if I input negative numbers.

  def length(s):
    return len(s)

   s = input("Enter the String: ")
    try:
        if (type(int(s)))==int :
            print("You input an integer")

    except ValueError:      
        print("it is a string with length " + str(length(s)))   
查看更多
栀子花@的思念
6楼-- · 2018-12-31 04:46
a=10

isinstance(a,int)  #True

b='abc'

isinstance(b,int)  #False
查看更多
泪湿衣
7楼-- · 2018-12-31 04:47

I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.

This was the solution that ended up working well for me to force an answer I wanted:

player_number = 0
while player_number != 1 and player_number !=2:
    player_number = raw_input("Are you Player 1 or 2? ")
    try:
        player_number = int(player_number)
    except ValueError:
        print "Please enter '1' or '2'..."

I would get exceptions before even reaching the try: statement when I used

player_number = int(raw_input("Are you Player 1 or 2? ") 

and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.

查看更多
登录 后发表回答