Diagram
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)
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
You can see that the str() function resolves the error.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.