Python 3 - TypeError: a byte object needed, not 'str'

I am working on a lesson from Udacity, and I have a problem trying to figure out if the result from this site returns true or false. I get a TypeError with the code below.

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

The output is b'true' , and I'm not sure where this' b' comes from.

+5
source share
1 answer

In python 3, the default string is unicode . b in b'true' means that the string is a byte string and not a unicode. If you do not want this to be possible:

  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 automatically close the urlopen connection.

+7
source

Source: https://habr.com/ru/post/1258694/


All Articles