2011-08-16 38 views
1

刚开始接触蟒蛇,并试图将下面的代码位的Python 3.2类型错误:不支持的操作数(个),%:“NoneType”和“海峡”

my_name = 'Joe Bloggs' 
my_age = 25 
my_height = 71 # inches 
my_weight = 203 #lbs approximate, converted from ~14.5 stones 
my_eyes = 'Blue' 
my_teeth = 'White' 
my_hair = 'Brown' 

print("Let's talk about %s") % my_name 
print ("He's %d inches tall.") % my_height 
print ("He's %d pounds heavy.") % my_weight 
print ("Actually that's not too heavy") 
print ("He's got %s eyes and %s hair.") % (my_eyes, my_hair) 
print ("His teeth are usually %s depending on the coffee.") % my_teeth 

我获得第9行的错误(第一个打印语句): TypeError:不支持的操作数为%:'NoneType'和'str'

即使在尝试使用{0}和。时,我仍然无法解决它。格式化方法,有什么想法?

回答

9

你想关闭括号移动到行的末尾:print ("He's %d inches tall." % my_height)

这是因为在Python 3,print是一个函数,所以你申请的%操作打印功能的结果,这是None。你需要的是将%运算符应用于格式字符串和你想替换的字符串,然后将该运算的结果发送到print()

编辑:正如GWW指出的,这种字符串格式已被弃用在Python 3.1中。你可以找到更多信息有关str.format,它取代了%运营商,在这里:http://docs.python.org/library/stdtypes.html#str.format

然而,因为Python 2.x的是在大多数生产环境的常态,它仍然是有用的熟悉%运营商。

+1

他应该使用str.format而不是'%'作为字符串格式,因为它已经在python 3.1中折旧了,将来会被删除。 – GWW

+0

+1,完美答案。 (GWW部分除外):P) –

+1

@GWW我已经添加到解决此问题的答案中。 –

相关问题