且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python 2.x中检查输入是字符串还是整数?

更新时间:2023-11-28 22:42:16

input()将接受并评估您的输入,然后再将其交付给您.也就是说,如果用户输入exit(),则您的应用程序将退出.从安全的角度来看,这是不希望的.您可能想使用raw_input()代替.在这种情况下,您可以期望返回的值是一个字符串.

input() will take and evaluate your input before handing it over to you. That is, if the user enters exit(), your application will exit. This is undesirable from a standpoint of security. You would want to use raw_input() instead. In this case you can expect the returned value to be a string.

如果您仍然想检查字符串内容是否可以转换为(整数)数字,请按照此处讨论的方法进行操作:

If you still want to check if the strings content is convertible to a (integer) number, please follow the approach discussed here:

简短概述:只需尝试将其转换为数字,然后查看是否失败.

A short outline: Just try to convert it to a number and see if it fails.

示例(未经测试):

value = raw_input()
try:
    int(value)
    print "it's an integer number"
except ValueError:
    print "it's a string"

供参考:

  • https://docs.python.org/2/library/functions.html#int
  • https://docs.python.org/2/library/functions.html#input
  • https://docs.python.org/2/library/functions.html#raw_input

请注意,input()函数的语义随Python 3改变:

Note that the semantics of the input() function change with Python 3: