TypeError: expected string or bytes-like object error typically 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 this error, use the “str()” function. It converts a value of any type to a string.
Flowchart
Causes of the error
- Passing a data type other than a string or bytes-like object to a function that expects string/bytes.
- The variable expected to be a string or bytes might be None.
- This error is common when using the re module for regular expressions if the pattern or the string to be searched is not a string or bytes-like object.
- If the data is not properly formatted as a string or bytes-like object while reading or writing files.
- If the object being encoded/decoded is not of the correct type.
Reproducing the error
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)
Output
TypeError: expected string or bytes-like object
The re.sub() function expects the first argument to be a string and the second argument to be a string, list, 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)
Output
HELC
That’s all!