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

Diagram of How to Fix TypeError: expected string or bytes-like object

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.