Python 3.2 类型错误:不支持的操作数:'NoneType' 和 'str
我刚开始学习Python,试了下面这段代码
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} 和 .format 方法也没能解决这个问题,有什么建议吗?
1 个回答
9
你想把关闭的小括号移到行的末尾:print ("He's %d inches tall." % my_height)
这是因为在Python 3中,print
是一个函数,所以你把%
这个操作符用在了print函数的结果上,而这个结果是None
。你其实想要的是把%
操作符用在格式字符串和你想替换的字符串上,然后把这个操作的结果传给print()
。
补充说明:正如GWW所指出的,这种字符串格式化的方法在Python 3.1中已经不推荐使用了。你可以在这里找到关于str.format
的更多信息,它取代了%
操作符:http://docs.python.org/library/stdtypes.html#str.format
不过,由于在大多数生产环境中,Python 2.x仍然是主流,所以熟悉%
操作符还是很有用的。