如何检查python 2.7中的原始输入是否为整数? [英] How do I check if raw input is integer in python 2.7?

查看:158
本文介绍了如何检查python 2.7中的原始输入是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可用于检查 raw_input 是否为整数?

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 isinstance(raw_input("number: ")), int)

但是当我运行它并输入 4 时,我获取 FALSE
我是python的新手,任何帮助都会受到赞赏。

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

推荐答案

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

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

使用 try:int(...)...除了ValueError

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

或使用 str.isdigit

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

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

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

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

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'

这篇关于如何检查python 2.7中的原始输入是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆