【问题标题】:Why does %r work while %d does in some cases even though there is a number为什么 %r 工作而 %d 在某些情况下工作,即使有一个数字
【发布时间】:2015-11-04 10:32:44
【问题描述】:

这里是 Python 初学者。想问你一个很简单的问题。

这是第一个示例代码:-

print "I will \"Add\" any two number that you type."
x = raw_input("What is the first number?")
y = raw_input("What is the second number?")

z = x + y

print "So, %d plus %d equals to %d" % (x, y, z)

在最后一行使用 %d 会出现错误:

   TypeError: %d format: a number is required, not str

这是第二个示例代码:-

print "I will \"Add\" any two number that you type."
x = raw_input("What is the first number?")
y = raw_input("What is the second number?")

z = x + y

print "So, %r plus %r equals to %r" % (x, y, z)

这并没有给出第一个代码给出的错误。

所以我的问题是为什么使用 %d 会给我错误但使用 %r 不会给我错误?

【问题讨论】:

  • %d 要求输入数值。 raw_input 为您提供字符串值。将两个字符串值相加会产生一个字符串值。因此,您在需要数值的地方传递了一个字符串值。
  • 您是否阅读过the documentation 的百分比转换类型?
  • 但基本上,%r 调用 repr

标签: python python-2.7


【解决方案1】:

每个变量都有一个未声明的隐式类型。类型是数字或字符串(文本)。 raw_input 总是返回一个字符串。

%d 标志尝试将变量格式化为数字。当它找到文本时,它会抛出一个错误。

【讨论】:

    【解决方案2】:

    当您通过 raw_input() 进行输入时,它会返回一个字符串,因此 xy 是字符串,而 zxy 的串联,而不是它的添加。不确定这是否是您的意图。如果您希望它们为 int ,请使用 int(raw_input(...)) 将它们转换为 int 。

    您得到的错误是因为 %d 期望 xyz(用于替换 %d )是整数(但它们实际上是字符串,因此出现错误)。

    %r 表示repr() 的输出,它接受任何类型的对象,因此它适用于您的第二种情况,尽管它会返回串联(而不是加法)。

    【讨论】:

    • 非常感谢,伙计。我现在明白了。所以,基本上 %d =整数,而不是其他任何东西。现在我有另一个简单的问题。当我运行上面的代码并输入两个数字时,我总是得到错误的答案。代码运行成功,但结果总是错误的。因此,如果我输入第一个数字为 7,第二个数字为 3,正确答案应该是,但程序告诉我答案是 73。为什么会发生这种情况?
    • 您是否阅读了答案中的第一段,它解释了您遇到问题的原因以及如何解决它
    • 非常感谢。我按照你的建议使用了“int(raw_input())”,现在它工作得很好。
    • 很高兴能为您提供帮助,如果答案对您有帮助,我建议您接受答案(通过单击答案左侧的勾号),它会对社区有所帮助。
    【解决方案3】:

    当您使用 raw_input 时,您必须将字符串转换为您想要的数据类型,例如在我的示例 1 中,我使用 int() 函数将变量 x 和 y 转换为数据类型 int。或者您可以只使用输入,Python 会为您处理,例如,如果您在输入时输入一个数字,Python 将假定是一个整数,如果您键入一个字符串,那么它将假定是一个字符串。

    ##Example 1:
    print "I will \"Add\" any two number that you type."
    x = raw_input("What is the first number?")
    y = raw_input("What is the second number?")
    
    z = int(x) + int(y)
    
    print "So, %d plus %d equals to %d" % (int(x), int(y), z)
    
    ##Example 2:
    print "I will \"Add\" any two number that you type."
    x = input("What is the first number?")
    y = input("What is the second number?")
    
    z = x + y
    
    print "So, %d plus %d equals to %d" % (x, y, z)
    

    【讨论】:

    • 非常感谢。我现在明白了。我喜欢你的示例 1,我从来没有这样想过。
    【解决方案4】:

    per https://docs.python.org/2/library/functions.html#raw_input raw_input 接受您的输入并将其分配为字符串。

    %d 只格式化数字。

    per https://docs.python.org/2/library/string.html#format-specification-mini-language(很难找到,%r 没有很好的文档记录) %r 使用 convert_field 将变量转换为一个表示,如果解析将得到相同的值。

    我相信 + 将两个字符串(x 和 y)强制转换为数字,以便它们可以相加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2019-02-25
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多