TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

孤人 提交于 2019-12-17 23:38:31

问题


So I am VERY new to programming and I started with Python 3. I started reading "Learn Python the Hard Way". Now, I got to a point where I had this code:

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s" % (binary, do_not)

print(x)
print(y)
print("I said: %r") % x

I do not really know the difference between %r, %s and %d. The error I get is TypeError: unsupported operand type(s) for %: 'NoneType' and 'str' No idea what to do and how to fix it. Please explain how I can actually make it work and why it won't work. Also, what is the difference between %r,d and s? Any useful links? Thank you in advance.


回答1:


You want to apply % to the string instead:

print("I said: %r" % x)

Your code is applying it to the return value of the print() call, which returns None.

Alternatively, you can switch to using str.format():

print("I said: {!r}".format(x))



回答2:


You are calling the % outside of the print() function. This tries to see if the actual function print can be printed as %r, and because print doesn't return anything, it tries to get %r for the value None (hence the NoneType error). Change it to:

print("I said: %r" %(x))

The following code:

#!/usr/local/bin/python3
x = "Hello"
print ("Hello World! %s") %(x)

Raises the following error:

Hello World! %s
Traceback (most recent call last):
  File "main.py", line 3, in 
    print ("Hello World! %s") %(x)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

Changing the code to the following works:

#!/usr/local/bin/python3
x = "Hello"
print ("Hello World! %s" %(x))

Output:

Hello World! Hello


来源:https://stackoverflow.com/questions/23372824/typeerror-unsupported-operand-types-for-nonetype-and-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!