Last updated: Apr 8, 2024
Reading timeยท4 min
The Python "TypeError: expected string or bytes-like object" occurs when you pass a non-string argument to a function that expects a string.
To solve the error, make sure to call the function with a string argument instead.
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.
The re.sub()
method takes 3 arguments:
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) # ๐๏ธ '___'
We used the str()
class to convert the integer to a string when calling
re.sub()
.
You might also be iterating over a sequence and calling the re.sub()
method
with each item.
str()
class.import re my_list = [0, 10, 100] new_list = [] for item in my_list: result = re.sub(r'[0-9]', '_', str(item)) print(result) new_list.append(result) print(new_list) # ๐๏ธ ['_', '__', '___']
We used a for loop to iterate over the list.
On each iteration, we pass the current item to the str()
class before using
re.sub()
.
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(repr(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.
Here is an example of how to solve the error when working with lists.
import re from ast import literal_eval my_list = [5, 'a', 0, 'b', 1, 'c', 2, 6] # โ remove letters from a list my_str = re.sub(r'[a-zA-Z]+', '', str(my_list)) print(my_str) # ๐๏ธ [5, '', 0, '', 1, '', 2, 6] # โ remove empty strings from a string new_str = my_str.replace("''", '') print(new_str) # ๐๏ธ [5, , 0, , 1, , 2, 6] # โ remove double commas from a string new_str = new_str.replace(", ,", ',') print(new_str) # ๐๏ธ [5, 0, 1, 2, 6] # โ convert the string representation of list to list my_list = literal_eval(new_str) print(my_list) # ๐๏ธ [5, 0, 1, 2, 6] print(type(my_list)) # ๐๏ธ <class 'list'>
literal_eval()
method to convert the string to
a list.You might also get the error when using the re.findall()
method.
re.findall()
Here is an example of how the error occurs when using re.findall()
.
import re my_int = 100 # โ๏ธ TypeError: expected string or bytes-like object, got 'int' result = re.findall(r'[0-9]', my_int)
To solve the error, convert the second argument in the call to findall()
to a
string.
import re my_int = 100 result = re.findall(r'[0-9]', str(my_int)) print(result) # ๐๏ธ ['1', '0', '0']
We used the str()
class to convert a value to a string before calling
re.findall()
.
Here is another 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 was make sure we passed a string as the second argument to the
re.findall
method.
The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.
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.
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.