Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

   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 prints b'true' and I'm not really sure where that 'b' is coming from.

like image 736
John Snow Avatar asked Oct 24 '16 05:10

John Snow


People also ask

How do you fix TypeError a bytes-like object is required not str?

To solve the Python "TypeError: a bytes-like object is required, not 'str'", encode the str to bytes, e.g. my_str. encode('utf-8') . The str. encode method returns an encoded version of the string as a bytes object.

What is a bytes-like object in Python?

In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable. Data is converted into byte form before it is stored on a computer.

How do you write bytes in Python?

Write Bytes to File in Python Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.


1 Answers

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.

like image 179
JClarke Avatar answered Oct 09 '22 08:10

JClarke