TypeError: expected string or bytes-like object in Python


Borislav Hadzhiev

Wed Apr 20 20223 min read


Photo by Sean

TypeError: expected string or bytes-like object in Python #

The Python "TypeError: expected string or bytes-like object" occurs when we pass an argument of a different type to a method that expects a string argument, e.g. re.sub(). To solve the error, make sure to pass a string argument to the method.

typeerror expected string or bytes like object

Here is an example of how the error occurs.

import re my_int = 100 # ⛔️ TypeError: expected string or bytes-like object result = re.sub(r'[0-9]', '_', my_int) # 👈️ third arg must be str

We passed an integer as the third argument to the re.sub method, but the method expects a string argument.

One way to solve the error is to use the str() class to convert the value to a string.

import re my_int = 100 # ✅ convert to str result = re.sub(r'[0-9]', '_', str(my_int)) print(result) # 👉️ '___'

You might also be iterating over a sequence and calling the re.sub() method with each item.

If you aren't sure whether all of the items in the sequence are strings, pass each to the str() class.

If your sequence stores None values, provide an empty string as a fallback.

import re my_value = None result = re.sub(r'[0-9]', '_', my_value or '') print(result) # 👉️ ''

The expression None or '' evaluates to an empty string which helps us avoid the error.

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

If the pattern isn't found, the string is returned as is.

You might also get the error when using the re.findall() method.

Here is an example of how the error occurs when using the re.findall() method..

import re with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() # 👈️ this is a list # ⛔️ TypeError: expected string or bytes-like object m = re.findall(r'\w+th', lines) # 👈️ passing list instead of str

We passed a list to the re.findall method, but the method takes a string argument.

To solve the error, call the read() method on the file object to get a string of the file's contents and pass the string to the findall method.

import re with open('example.txt', 'r', encoding='utf-8') as f: my_str = f.read() print(type(my_str)) # 👉️ <class 'str'> m = re.findall(r'\w+th', my_str) print(m) # 👉️ ['fourth', 'fifth']

The example assumes that you have a file named example.txt with the following contents:

first second third fourth fifth

All we had to do is make sure we pass a string as the second argument to the re.findall method.

If you got the error while trying to read a JSON file, use the json.load() method.

import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) # ✅ call json.load() with file obj print(my_data) # 👉️ {'name': 'Alice', 'age': 30} print(my_data['name']) # 👉️ 'Alice' print(type(my_data)) # 👉️ <class 'dict'>

The code sample above assumes that you have an example.json file in the same directory.

{"name": "Alice", "age": 30}

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

If the error persists, use your IDE to check the type of the method's parameters.

One of the arguments the method takes must be of type str and you are passing a value of a different type.

If you aren't sure what type of object a variable stores, use the built-in type() class.

my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # 👉️ <class 'dict'> print(isinstance(my_dict, dict)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.