如何在Python 2.x中检查输入是字符串还是整数? [英] How do I check if an input is a string or int in Python 2.x?

查看:156
本文介绍了如何在Python 2.x中检查输入是字符串还是整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查输入是单词还是数字.

I am trying to check if an input is a word or a number.

var = input("var: ")

if isinstance(var, str):
    print "var = word"

else:
   print "var = number"

这是我想出的代码,但不幸的是它不起作用; 我是python和程序设计的新手,所以我不知道很多命令, 任何建议将不胜感激^^

This is the code I came up with but sadly doesn't work; I'm new to python and programming in general so I don't know alot of commands, any suggestion would be appreciated ^^

推荐答案

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:

这篇关于如何在Python 2.x中检查输入是字符串还是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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