如何在 python 2.7 中检查原始输入是否为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19440952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:44:57  来源:igfitidea点击:

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

pythonstringpython-2.7integerraw-input

提问by Alejandro Veintimilla

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

有没有一种方法可以用来检查 araw_input是否为整数?

I found this method after researching in the web:

我在网上研究后发现了这个方法:

print isinstance(raw_input("number: ")), int)

but when I run it and input 4for example, I get FALSE. I'm kind of new to python, any help would be appreciated.

但是当我运行它并输入4例如时,我得到FALSE. 我对 python 有点陌生,任何帮助将不胜感激。

采纳答案by falsetru

isinstance(raw_input("number: ")), int)always yields Falsebecause raw_inputreturn string object as a result.

isinstance(raw_input("number: ")), int)总是产生,False因为结果raw_input返回字符串对象。

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

使用try: int(...) ... except ValueError

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

or use str.isdigit:

或使用str.isdigit

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

NOTEThe second one yields Falsefor -4because it contains non-digits character. Use the second one if you want digits only.

注意第二个产生Falsefor-4因为它包含非数字字符。如果您只想要数字,请使用第二个。

UPDATEAs J.F. Sebastian pointed out, str.isdigitis locale-dependent (Windows). It might return Trueeven int()would raise ValueError for the input.

更新正如 JF Sebastian 指出的那样,str.isdigit是依赖于语言环境的(Windows)。它可能会返回True甚至int()会为输入引发 ValueError。

>>> 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'

回答by Dietrich Epp

You can do it this way:

你可以这样做:

try:
    val = int(raw_input("number: "))
except ValueError:
    # not an integer

回答by user5322265

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'),

`

`

回答by Frank Musteman

def checker():
  inputt = raw_input("how many u want to check?")
  try:
      return int(inputt)
  except ValueError:
      print "Error!, pls enter int!"
      return checker()

回答by Elf Machine

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

试试这个方法 .isdigit(),见下面的例子。

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)