How do I check if raw input is integer in python 2.7?

前端 未结 5 1218
庸人自扰
庸人自扰 2020-11-28 15:28

Is there a method that I can use to check if a raw_input is an integer?

I found this method after researching in the web:

print isinsta         


        
相关标签:
5条回答
  • 2020-11-28 16:19
    def checker():
      inputt = raw_input("how many u want to check?")
      try:
          return int(inputt)
      except ValueError:
          print "Error!, pls enter int!"
          return checker()
    
    0 讨论(0)
  • 2020-11-28 16:19

    Try this method .isdigit(), see example below.

    user_input = raw_input()
    if user_input.isdigit():
        print "That is a number."
    
    else:
        print "That is not a number."
    

    If you require the input to remain digit for further use, you can add something like:

    new_variable = int(user_input)
    
    0 讨论(0)
  • 2020-11-28 16:21

    You can do it this way:

    try:
        val = int(raw_input("number: "))
    except ValueError:
        # not an integer
    
    0 讨论(0)
  • 2020-11-28 16:25

    isinstance(raw_input("number: ")), int) always yields False because raw_input return string object as a result.

    Use try: int(...) ... except ValueError:

    number = raw_input("number: ")
    try:
        int(number)
    except ValueError:
        print False
    else:
        print True
    

    or use str.isdigit:

    print raw_input("number: ").isdigit()
    

    NOTE The second one yields False for -4 because it contains non-digits character. Use the second one if you want digits only.

    UPDATE As J.F. Sebastian pointed out, str.isdigit is locale-dependent (Windows). It might return True even int() would raise ValueError for the input.

    >>> import locale
    >>> locale.getpreferredencoding()
    'cp1252'
    >>> '\xb2'.isdigit()  # SUPERSCRIPT TWO
    False
    >>> locale.setlocale(locale.LC_ALL, 'Danish')
    'Danish_Denmark.1252'
    >>> '\xb2'.isdigit()
    True
    >>> int('\xb2')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '\xb2'
    
    0 讨论(0)
  • 2020-11-28 16:31

    here is my solution

    `x =raw_input('Enter a number or a word: ')
    y = x.isdigit()
    if (y == False):
        for i in range(len(x)):
            print('I'),
    else:
        for i in range(int(x)):
            print('I'),
    

    `

    0 讨论(0)
提交回复
热议问题