【问题标题】:TypeError: unsupported operand type(s) for /: 'str' and 'int'TypeError:不支持的操作数类型/:'str'和'int'
【发布时间】:2012-12-31 13:08:58
【问题描述】:

在 Python 2.7 中:

a=80
b=100

def status(hp, maxhp):
    print "You are at %r percent health." % hp*100/maxhp

status(a,b)

返回:

TypeError: /: 'str' 和 'int' 的操作数类型不受支持

我已经尝试在每个变量和每个变量组合周围放置 int()。

【问题讨论】:

    标签: python string types int typeerror


    【解决方案1】:

    % 运算符的优先级高于*/

    你的意思是:

    "You are at %r percent health." % (hp * 100 / maxhp)
    

    你得到的是:

    ("You are at %r percent health." % hp) * 100 / maxhp
    

     

    编辑:实际上,我错了。它们具有相同的优先级,因此从左到右应用。

    Docs: operator precedence

    【讨论】:

    • 谢谢,我从来没有被告知在这种情况下模数被认为是一个操作数,或者它在操作顺序中的位置。我最终通过创建另一个变量并将其输入字符串来修复它。
    【解决方案2】:

    您需要将括号包裹在表达式周围,以便在尝试将结果替换到字符串之前对其进行全面评估。

    类似:

    print "my string with this '%d' value" % (hp * 100 / maxhp)
    

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 2012-11-29
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多