【发布时间】: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