Python 3 - TypeError:需要一个类似字节的对象,而不是“str" [英] Python 3 - TypeError: a bytes-like object is required, not 'str'
问题描述
我正在学习 Udacity 的课程,但在尝试确定此站点的结果返回 true 还是 false 时遇到了一些问题.我用下面的代码得到了 TypeError.
I'm working on a lesson from Udacity and am having some issue trying to find out if the result from this site returns true or false. I get the TypeError with the code below.
from urllib.request import urlopen
#check text for curse words
def check_profanity():
f = urlopen("http://www.wdylike.appspot.com/?q=shit")
output = f.read()
f.close()
print(output)
if "b'true'" in output:
print("There is a profane word in the document")
check_profanity()
输出打印 b'true'
并且我不确定那个 'b' 是从哪里来的.
The output prints b'true'
and I'm not really sure where that 'b' is coming from.
推荐答案
在 python 3 中,字符串默认为 unicode
.b'true'
中的 b
表示该字符串是字节字符串而不是 unicode.如果你不想要,你可以这样做:
In python 3 strings are by default unicode
. The b
in b'true'
means that the string is a byte string and not unicode. If you don't want that you can do:
from urllib.request import urlopen
#check text for curse words
def check_profanity():
with urlopen("http://www.wdylike.appspot.com/?q=shit") as f:
output = f.read().decode('utf-8')
if output:
if "true" in output:
print("There is a profane word in the document")
check_profanity()
使用 with
将自动关闭 urlopen
连接.
Using with
will close the urlopen
connection automatically.
这篇关于Python 3 - TypeError:需要一个类似字节的对象,而不是“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!