Python 3 - TypeError: a bytes-like object is required, not 'str'

前端 未结 1 1247
庸人自扰
庸人自扰 2021-01-02 07:31

I\'m working on a lesson from Udacity and am having some issue trying to find out if the result from this site returns true or false. I get the TypeError with the code below

相关标签:
1条回答
  • In python 3 strings are by default unicode. The b in b'true' means that the string is a byte string and not unicode. If you don't want that you can do:

     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()
    

    Using with will close the urlopen connection automatically.

    0 讨论(0)
提交回复
热议问题