刚刚开始使用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方法时都没能绕过它,有什么想法吗?
要将结束符移到行的末尾:
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然而,由于Python2.x是大多数生产环境中的标准,因此熟悉
%
操作符仍然很有用。相关问题 更多 >
编程相关推荐