Last updated: Apr 8, 2024
Reading timeยท2 min

The Python "TypeError: cannot use a string pattern on a bytes-like object" occurs when we try to use a string pattern to match a bytes object.
To solve the error, use the decode() method to decode the bytes object, e.g.
my_bytes.decode('utf-8').

Here is an example of how the error occurs.
import re my_bytes = b'apple,banana,kiwi' # โ๏ธ TypeError: cannot use a string pattern on a bytes-like object m = re.search("apple", my_bytes)
We tried to use a string pattern to match a bytes object which is not supported.
One way to solve the error is to decode the bytes object into a string.
import re my_bytes = b'apple,banana,kiwi' m = re.search("apple", my_bytes.decode('utf-8')) print(m) # ๐๏ธ <re.Match object; span=(0, 5), match='apple'>

The bytes.decode() method returns a
string decoded from the given bytes. The default encoding is utf-8.
Now we used a string pattern to find a match in a string, which is allowed.
Alternatively, you can use a bytes-pattern on a bytes-like object.
import re my_bytes = b'apple,banana,kiwi' # ๐๏ธ notice b'' prefix m = re.search(b"apple", my_bytes) print(m) # ๐๏ธ <re.Match object; span=(0, 5), match=b'apple'>

Notice that the first and the second arguments we passed to re.search are
bytes objects.
We previously used the bytes.decode() method. However, if you need to convert
a string to a bytes object, you have to use the str.encode() method.
my_str = 'bobbyhadz.com' my_bytes = my_str.encode(encoding='utf-8') print(my_bytes) # ๐๏ธ b'bobbyhadz.com'
The str.encode() method returns an
encoded version of the string as a bytes object. The default encoding is
utf-8.
string to a bytes object and decoding is the process of converting a bytes object to a string.If you aren't sure what type 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_bytes = b'James Doe' print(type(my_bytes)) # ๐๏ธ <class 'bytes'> print(isinstance(my_bytes, bytes)) # ๐๏ธ 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.