How to Fix: Typeerror: expected string or bytes-like object

This code is downloading 10 images from a website and saving them in a folder called images. It uses the requests library to get the image URLs, and the json library to parse the response from the server. It also uses the os library to create the images folder if it doesn’t exist and the time library to add a delay between each download.


One error you may encounter when using Python is:

TypeError: expected string or bytes-like object

This error typically occurs when you attempt to use the re.sub() function to replace certain patterns in an object but the object you’re working with is not composed entirely of strings.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following list of values:

#define list of values
x = [1, 'A', 2, 'B', 5, 'C', 'D', 'E']

Now suppose we attempt to replace each non-letter in the list with an empty string:

import re

#attempt to replace each non-letter with empty string
x = re.sub('[^a-zA-Z]', '', x)

TypeError: expected string or bytes-like object

We receive an error because there are certain values in the list that are not strings.

How to Fix the Error

The easiest way to fix this error is to convert the list to a string object by wrapping it in the str() operator:

import re

#replace each non-letter with empty string
x = re.sub('[^a-zA-Z]', '', str(x))

#display results
print(x)

ABCDE

Notice that we don’t receive an error because we used str() to first convert the list to a string object.

The result is the original list with each non-letter replaced with a blank.

Note: You can find the complete documentation for the re.sub() function .

 

x