Python 的 type() 函数及其“if”相关问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17333021/
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
Python's type() function and its 'if' related problems
提问by Nick Robertson
So I have the following code:
所以我有以下代码:
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
if input_type == "str":
print "Your string was %s." % user_input
elif input_type == "int":
input_type = int(input_type)
print "Your integer was %d." % user_input
elif input_type == "float":
input_type = int(input_value)
print "Your float was %d." % user_input
else:
print "You did not enter an acceptable input."
This does notwork — I believe because of the if
— so I changed it to be:
这不起作用——我相信是因为if
——所以我把它改成:
if "str" in input_type
and "int"
for the float and integer, but get an error:
和"int"
浮点数和整数,但得到一个错误:
Traceback (most recent call last):
File "types.py", line 4, in <module>
if "str" in input_type:
TypeError: argument of type 'type' is not iterable
Why do I get this and how can I fix it?
为什么我会得到这个,我该如何解决?
采纳答案by abarnert
There are a number of problems here.
这里有很多问题。
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
Since raw_input
always returns a string, input_type
will always be str
here.
由于raw_input
总是返回一个字符串,所以input_type
会一直在str
这里。
if input_type == "str":
print "Your string was %s." % user_input
input_type
will be str
—that is, the actual object representing the string type—not "str"
, which is just a string. So, this will never be true, and neither will any of your other tests.
input_type
will str
- 也就是说,表示字符串类型的实际对象 - not "str"
,它只是一个字符串。所以,这永远不会是真的,你的任何其他测试也不会。
Changing this to:
将此更改为:
if "str" in input_type:
… can't possibly help anything, unless you're expecting input_type
to be either a collection of strings, or a longer string with "str"
in the middle of it somewhere. And I can't imagine why you'd expect either.
... 不可能有任何帮助,除非您希望input_type
成为字符串的集合,或者"str"
中间某个地方的更长的字符串。我无法想象为什么你会期待。
These lines:
这些线路:
input_type = int(input_type)
… are trying to convert the input_type
—which, remember, is a type, like str
or int
, not the value—to an integer. That can't be what you want.
... 正在尝试将input_type
- 记住,它是一种类型,例如str
or int
,而不是值 - 转换为整数。那不可能是你想要的。
These lines:
这些线路:
print "Your integer was %d." % user_input
Are printing the original string you received from the user, not the thing you converted to an int
. This would work if you used %s
rather than %d
, but it's probably not what you were trying to do.
正在打印您从用户那里收到的原始字符串,而不是您转换为int
. 如果您使用%s
而不是%d
,这会起作用,但这可能不是您想要做的。
print "Your float was %d." % user_input
Even if you fix the previous problem, you can't use %d
to print floats.
即使解决了之前的问题,也无法用于%d
打印浮点数。
Next, it's almost always a bad idea to test things by comparing types.
接下来,通过比较类型来测试事物几乎总是一个坏主意。
If you reallyneed to do it, it's almost always better to use isinstance(user_input, str)
not type(user_input) == str
.
如果你真的需要这样做,使用isinstance(user_input, str)
not几乎总是更好type(user_input) == str
。
But you don't need to do it.
但你不需要这样做。
In fact, it's generally better to "ask forgiveness than permission". The right way to find out if something can be converted to an integer is to just try to convert it to an integer, and handle the exception if it can't:
事实上,“请求宽恕而不是许可”通常更好。确定某些东西是否可以转换为整数的正确方法是尝试将其转换为整数,如果不能,则处理异常:
try:
int_value = int(user_input)
print "Your integer was %d." % int_value
except ValueError:
# it's not an int
回答by Amadan
First of all, "does not work" is not useful. Please in the future explain exactly how it's not working, what you expect and what you get that is unsatisfactory.
首先,“不起作用”是没有用的。请在将来准确解释它是如何不起作用的,您期望什么以及您得到什么不满意。
Now to your problem: raw_input
will always return a string. It is up to you to see if contents of that string conform to something that looks like an integer or a float, and convert accordingly. You know how to convert; the conformity testing would normally be done through a regular expression.
现在解决您的问题:raw_input
将始终返回一个字符串。由您来查看该字符串的内容是否符合看起来像整数或浮点数的内容,并相应地进行转换。你知道如何转换;一致性测试通常通过正则表达式完成。
回答by dansalmo
You would need to use isinstance
and input
to get your code to do what you expect as follows:
您需要使用isinstance
并input
让您的代码执行您的期望,如下所示:
user_input = input("Enter an integer, string or float:")
if isinstance(user_input, str):
print "Your string was %s." % user_input
elif isinstance(user_input, int):
print "Your integer was %d." % user_input
elif isinstance(user_input, float):
print "Your float was %f." % user_input
else:
print "You did not enter an acceptable input."
raw_input
always returns a string.
raw_input
总是返回一个字符串。
When using input
, you must include ' or " around a string input. Also, never use input
like this because it can be very dangerous. Use the try except
method suggested by abarnert.
使用时input
,您必须在字符串输入周围包含 ' 或 "。此外,切勿input
像这样使用,因为这可能非常危险。请使用try except
abarnert 建议的方法。
回答by abarnert
While I don't think this is a true duplicate, Differences between isinstance() and type() in pythoncontains a very relevant answer and is good to read.
虽然我不认为这是一个真正的重复,但Python中isinstance() 和 type() 之间的差异包含一个非常相关的答案并且很好读。
You would ultimately want to write a try/except
that treats the data appropriately.
您最终会希望编写一个try/except
适当处理数据的程序。
if isinstance(user_input, str): #or basestring, if you prefer, but Python 3 apparently doesn't use it
useThisLikeAString(user_input)
try:
intInput = int(user_input)
useThisLikeAnInt(user_input)
except TypeError:
useThisLikeSomethingElse(user_input)
The accepted answer is totally right, in other words, but the link to that discussion is worthwhile.
换句话说,接受的答案是完全正确的,但该讨论的链接是值得的。
回答by Vivekananda Kuragayala
Add another variable to the code with value as string and do the type compare of that with other variables.
将另一个变量添加到代码中,值为字符串,并与其他变量进行类型比较。
a="test"
type(a)==type(user_input)
This will be simpler.
这会更简单。