[英]Python 3 - TypeError: a bytes-like object is required, not 'str'
我正在研究Udacity的一个教训,并且在尝试查看此站点的结果是返回true还是false时遇到了一些问题。 我使用下面的代码获得TypeError。
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'来自哪里。
在python 3中,字符串默认为unicode
。 b'true'
的b
表示字符串是字节字符串而不是unicode。 如果你不希望你能做到:
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
连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.