【问题标题】:Python 3 - TypeError: a bytes-like object is required, not 'str'Python 3 - TypeError:需要一个类似字节的对象,而不是“str”
【发布时间】:2017-03-05 19:36:29
【问题描述】:

我正在学习 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.x urllib unicode-string


【解决方案1】:

在 python 中,默认情况下 3 个字符串是 unicodeb'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 连接。

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多