Python 3 - TypeError:需要类似字节的对象,而不是'str'

Joh*_*now 6 urllib unicode-string python-3.x

我正在研究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()
Run Code Online (Sandbox Code Playgroud)

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

JCl*_*rke 8

在python 3中,默认情况下是字符串unicode.将bb'true'指字符串是一个字节字符串,不是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()
Run Code Online (Sandbox Code Playgroud)

使用withurlopen自动关闭连接.