python-3.x – Python 3 – TypeError:需要类似字节的对象,而不是’str’

前端之家收集整理的这篇文章主要介绍了python-3.x – Python 3 – TypeError:需要类似字节的对象,而不是’str’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究Udacity的一个教训,并且在尝试查看此站点的结果是返回true还是false时遇到了一些问题.我使用下面的代码获得TypeError.
  1. from urllib.request import urlopen
  2. #check text for curse words
  3. def check_profanity():
  4. f = urlopen("http://www.wdylike.appspot.com/?q=shit")
  5. output = f.read()
  6. f.close()
  7. print(output)
  8. if "b'true'" in output:
  9. print("There is a profane word in the document")
  10.  
  11. check_profanity()

输出打印b’true’,我不确定’b’来自哪里.

解决方法

在python 3中,字符串默认为unicode. b’true’中的b表示字符串是字节字符串而不是unicode.如果你不希望你能做到:
  1. from urllib.request import urlopen
  2. #check text for curse words
  3. def check_profanity():
  4. with urlopen("http://www.wdylike.appspot.com/?q=shit") as f:
  5. output = f.read().decode('utf-8')
  6. if output:
  7. if "true" in output:
  8. print("There is a profane word in the document")
  9.  
  10. check_profanity()

使用with将自动关闭urlopen连接.

猜你在找的Python相关文章