python-3.x – Python 3 – TypeError:需要类似字节的对象,而不
发布时间:2020-12-16 23:01:11 所属栏目:Python 来源:网络整理
导读:我正在研究Udacity的一个教训,并且在尝试查看此站点的结果是返回true还是false时遇到了一些问题.我使用下面的代码获得TypeError. from urllib.request import urlopen #check text for curse words def check_profanity(): f = urlopen("http://www.wdylike.
我正在研究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连接. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |