所以我有以下代码: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_inputelif input_type == "int": input_type = int(input_type) print "Your integer was %d." % user_inputelif input_type == "float": input_type = int(input_value) print "Your float was %d." % user_inputelse: print "You did not enter an acceptable input."我认为这是行不通的if,因此我将其更改为:if "str" in input_type和"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为什么会得到这个,我该如何解决?
3 回答

湖上湖
TA贡献2003条经验 获得超2个赞
首先,“不起作用”是没有用的。将来请确切说明它不起作用,您的期望以及所获得的令人满意的结果。
现在解决您的问题:raw_input
将始终返回一个字符串。由您决定该字符串的内容是否符合看起来像整数或浮点数的内容,然后进行相应的转换。你知道如何转换;合格性测试通常是通过正则表达式完成的。

呼唤远方
TA贡献1856条经验 获得超11个赞
虽然我不认为这是真正的重复,但是python中的isinstance()和type()之间的差异包含一个非常相关的答案,很容易阅读。
您最终将希望编写一个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)
换句话说,被接受的答案是完全正确的,但是与该讨论的链接是值得的。
添加回答
举报
0/150
提交
取消