Skip to main content
 首页 » 编程设计

Python 3.2 类型错误 : unsupported operands(s) for %: 'NoneType' and 'str'

2025年05月04日26wayfarer

刚刚开始使用 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 行(第一个 print 语句)出现错误: TypeError: %: 'NoneType' 和 'str' 不支持的操作数

即使尝试使用 {0} 和 .format 方法,我也无法解决这个问题,有什么想法吗?

请您参考如下方法:

您想将闭括号移动到行尾: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 是大多数生产环境中的规范,因此熟悉 % 运算符仍然很有用。