开发者

Python 3.2 TypeError: unsupported operands(s) for %: 'NoneType' and 'str'

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 开发者_如何学Pythonto 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜