Python 类型错误:% 不支持的操作数类型:'NoneType' 和 'str'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23372824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:51:17  来源:igfitidea点击:

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

pythonstring-formattingtypeerror

提问by user3586591

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:

所以我对编程非常陌生,我从 Python 3 开始。我开始阅读“Learn Python the Hard Way”。现在,我到了我有这个代码的地步:

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, %sand %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.

我真的不知道%r,%s和之间的区别%d。我得到的错误是TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'不知道该怎么做以及如何解决它。请解释我如何才能真正使它工作以及为什么它不起作用。另外,%r,d 和 s 有什么区别?任何有用的链接?先感谢您。

回答by Martijn Pieters

You want to apply %to the stringinstead:

要应用%的字符串,而不是:

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

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

您的代码将其应用于print()调用的返回值,该调用返回None.

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

或者,您可以切换到使用str.format()

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

回答by A.J. Uppal

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

您正在调用函数的%外部print()。这会尝试查看实际函数是否print可以打印为%r,并且由于print不返回任何内容,因此它尝试获取%r该值None(因此出现NoneType错误)。将其更改为:

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