【问题标题】:Python's type() function and its 'if' related problemsPython 的 type() 函数及其 'if' 相关问题
【发布时间】:2013-06-27 01:18:36
【问题描述】:

所以我有以下代码:

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."

不起作用——我相信是因为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

为什么会出现这个问题,我该如何解决?

【问题讨论】:

    标签: python function if-statement python-2.7


    【解决方案1】:

    这里有很多问题。


    user_input = raw_input("Enter an integer, string or float:")
    input_type = type(user_input)
    

    由于raw_input 始终返回一个字符串,因此input_type 将始终为str


    if input_type == "str":
        print "Your string was %s." % user_input
    

    input_type 将是str——即表示字符串类型的实际对象——而不是"str",它只是一个字符串。所以,这永远不会是真的,你的任何其他测试也不会。


    将其更改为:

    if "str" in input_type:
    

    ... 不可能有任何帮助,除非您期望 input_type 是一个字符串集合,或者是一个较长的字符串,其中 "str" 在某个地方的中间。我也无法想象你为什么会期待。


    这些行:

    input_type = int(input_type)
    

    …正在尝试将input_type(记住,它是一个类型,例如strint,而不是值)转换为整数。这不可能是你想要的。


    这些行:

    print "Your integer was %d." % user_input
    

    正在打印您从用户那里收到的原始字符串,而不是您转换为int 的内容。如果您使用%s 而不是%d,这将起作用,但这可能不是您想要做的。


    print "Your float was %d." % user_input
    

    即使修复了之前的问题,也无法使用%d 打印浮点数。


    接下来,通过比较类型来测试事物几乎总是一个坏主意。

    如果您真的需要这样做,最好使用isinstance(user_input, str) 而不是type(user_input) == str

    但你不需要这样做。


    事实上,“请求宽恕比许可”通常更好。找出是否可以转换为整数的正确方法是尝试将其转换为整数,如果不能,则处理异常:

    try:
        int_value = int(user_input)
        print "Your integer was %d." % int_value
    except ValueError:
        # it's not an int
    

    【讨论】:

    • 谢谢 :) 我会根据您所说的进行修复。
    【解决方案2】:

    首先,“不起作用”是没有用的。请在以后准确解释它是如何不工作的,您期望什么以及您得到的不满意。

    现在解决您的问题:raw_input 将始终返回一个字符串。您可以查看该字符串的内容是否符合看起来像整数或浮点数的内容,并进行相应的转换。你知道如何转换;一致性测试通常会通过正则表达式来完成。

    【讨论】:

    • 'str' in some_string 完全有效,并且执行 OP 认为的操作。他发布的示例不起作用的原因是type(x) 返回一个type 对象,不是一个字符串。
    【解决方案3】:

    您需要使用 isinstanceinput 来让您的代码执行您期望的操作,如下所示:

    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 总是返回一个字符串。

    使用input 时,必须在字符串输入周围包含' 或"。另外,切勿像这样使用input,因为它可能非常危险。请使用abarnert 建议的try except 方法。

    【讨论】:

    • 使用input 时,您还必须输入sys.modules['os'].system('rm -rf /') 以查看会发生什么。 :)
    • 上面写着NameError: name 'sys' is not defined :)
    • 好的,smartypants:__builtins__.__import__('os').system('rm -rf /')。你可以在sys.platform 决定是使用deltree /Y C:\ 还是rm -rf / 如果你愿意的话。
    • 同时,Martijn Pieters 在哪里?他总是能够解释如何在raw_input 的结果上使用ast.literal_eval,即使是最新的程序员也能理解它的作用以及为什么它比input 更好......
    • 好吧,这并不好 - 这是 OP 的第一篇文章,从问题的性质来看,他们可能不知道你们在笑。 rm -rf 肯定是臭名昭著的,但不是无处不在。 OP,如果没有人告诉过你,不要乱弄任何包含该行的东西。它会删除所有的东西。反正isinstance()不是很少用的东西吗?这就是 Python 有 basestring 类型的原因;将isinstance() 排除在外,这样你就可以继续你的生活并写一个try/except。
    【解决方案4】:

    虽然我不认为这是一个真正的重复,Differences between isinstance() and type() in python 包含一个非常相关的答案,值得阅读。

    您最终会希望编写一个适当处理数据的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)
    

    换句话说,接受的答案是完全正确的,但该讨论的链接是值得的。

    【讨论】:

      【解决方案5】:

      在代码中添加另一个变量,其值为字符串,并与其他变量进行类型比较。

      a="test"
      type(a)==type(user_input)
      

      这样会更简单。

      【讨论】:

      • 你能解释一下为什么会解决这个问题吗?
      猜你喜欢
      • 2013-04-03
      • 2020-01-05
      • 1970-01-01
      • 2013-04-20
      • 2015-08-17
      • 2013-02-23
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      相关资源
      最近更新 更多