TypeError: expected string or bytes-like object error typically occurs when “you are using or have defined is fed an integer or float.“
It also occurs when you 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.
To fix the TypeError: expected string or bytes-like object, you can use the “str()” function. Python str() function converts a value of any type to a string.
Reproducing the error using Python code
import re data = ['H', 'E', 2, 'L', 11, 'C', 19, 21] # The following line of code will generate the error data = re.sub('[^a-zA-Z]', '', data) print(data)
TypeError: expected string or bytes-like object
In our example, the data is a list of integers and strings, and the function cannot work on the list directly.
How to Fix it?
import re data = ['H', 'E', 2, 'L', 11, 'C', 19, 21] data = re.sub('[^a-zA-Z]', '', str(data)) print(data)
You can see that the str() function resolves the error.