【问题标题】:How to make if else work for python3 [duplicate]如何使 if else 适用于 python3 [重复]
【发布时间】:2016-07-26 02:07:35
【问题描述】:

我最近切换到了 Python 3,通常适用于 Python 2 的常规操作不适用于 Python 3。我已经能够修复其余部分,但我正在努力解决这个问题。我无法检查某物是什么“类型”。

raw = input("Please give me a number, string\
 or decimal: ")
if type(raw) == int:
    print("You entered a number")
elif type(raw) == float:
    print("You entered a decimal")
elif type(raw) == str:
    print("You entered a string")
else:
    print("error please try again")

`

【问题讨论】:

  • 应该是你输入了一个字符串 :) 对吗?

标签: python python-3.4


【解决方案1】:

在 python3.x 中,input 始终返回 str 类型的对象。与 python2.x 等效的是eval(input('...'))。与随时使用eval 一样,请确保您绝对相信输入不会对您的程序或计算机造成恶意...

更好的方法是使用类似ast.literal_eval 的东西(它将安全地评估您的文字)或自己进行检查...

def is_int_str(s):
    """Checks if a string (s) represents a python integer."""
    try:
        int(s)
    except ValueError:
        return False
    return True

然后编写类似的float 版本是微不足道的......

【讨论】:

  • 字符串库中有 isdigit/isnumeric 方法,应该在这里使用。
  • @story645 -- 不... EAFP :-)。只需try 将字符串转换为适当的类型,看看它是否有效...
  • 嗯,我喜欢这个字符串库......但实际上,任何不是 eval 的东西都可能是好的。
猜你喜欢
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 2019-04-20
  • 2014-08-08
  • 2015-11-03
  • 1970-01-01
  • 2015-10-28
相关资源
最近更新 更多