Python 3.2 TypeError:% 不支持的操作数:'NoneType' 和 'str' [英] Python 3.2 TypeError: unsupported operands(s) for %: 'NoneType' and 'str'
问题描述
刚开始使用python并尝试了以下代码
my_name = 'Joe Bloggs'我的年龄 = 25my_height = 71 # 英寸my_weight = 203 #lbs 近似值,从 ~14.5 石头转换而来my_eyes = '蓝色'my_teeth = '白色'my_hair = '棕色'print("让我们谈谈 %s") % my_nameprint ("他有 %d 英寸高.") % my_heightprint ("他重 %d 磅.") % my_weight打印(其实还不算太重")print ("他有 %s 的眼睛和 %s 的头发.") % (my_eyes, my_hair)打印(根据咖啡的不同,他的牙齿通常是 %s.")% my_teeth
我收到第 9 行(第一个打印语句)的错误,其中说:类型错误:% 不支持的操作数:'NoneType' 和 'str'
即使尝试使用 {0} 和 .format 方法,我也无法绕过它,有什么想法吗?
您想将右括号移到行尾:print ("He's %d inches high." % 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 是大多数生产环境的规范,熟悉 %
操作符仍然很有用.
Just getting started with python and tried the following bit of code
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
I get an error for line 9 (the first print statement) which says: TypeError: unsupported operands(s) for %: 'NoneType' and 'str'
I haven't been able to get around it even when trying to use the {0} and .format method, any ideas?
You want to move the close paren to the end of the line: print ("He's %d inches tall." % my_height)
That's because in Python 3, print
is a function, so you are applying the %
operator to the results of the print function, which is None
. What you want is to apply the %
operator to the format string and the string you wish to substitute, and then send the result of that operation to print()
.
EDIT: As GWW points out, this kind of string formatting has been deprecated in Python 3.1. You can find more information about str.format
, which replaces the %
operator, here: http://docs.python.org/library/stdtypes.html#str.format
However, since Python 2.x is the norm in most production environments, it's still useful to be familiar with the %
operator.
这篇关于Python 3.2 TypeError:% 不支持的操作数:'NoneType' 和 'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!