Sequence item 0: expected str instance, bytes found (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

Sequence item 0: expected str instance, bytes found (Python) #

The Python "TypeError: sequence item 0: expected str instance, bytes found" occurs when we call the join() method with an iterable that contains one or more bytes objects. To solve the error, prefix the string separator with b, e.g. result = b''.join(my_list).

typeerror sequence item 0 expected str instance bytes found

Here is an example of how the error occurs.

main.py
my_list = [b'a', b'b', b'c'] # ⛔️ TypeError: sequence item 0: expected str instance, bytes found result = ''.join(my_list)

The issue is that we are trying to use a string separator to join a list containing bytes objects.

One way to solve the error is to prefix the string separator with a b to turn it into a bytes object.

main.py
my_list = [b'a', b'b', b'c'] # 👇️ using b'' prefix result = b''.join(my_list) print(result) # 👉️ b'abc' # 👇️ optionally decode bytes to str my_str = result.decode('utf-8') print(my_str) # 👉️ 'abc'

After joining the bytes objects, you can optionally use the decode() method to get a string.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8.

If your list contains both bytes objects and strings, use the map() function to decode each bytes object.

main.py
my_list = [b'a', 'b', b'c', 'd'] result = ''.join(map(lambda item: item if isinstance( item, str) else item.decode('utf-8'), my_list)) print(result) # 👉️ 'abcd'

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

On each iteration, we check if the value is a string and if it is we return it, otherwise we decode the value and return the result.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

The string the method is called on is used as the separator between elements.

main.py
my_list = [1, 2, 'a', 'b'] result = '_'.join(map(str, my_list)) print(result) # 👉️ '1_2_a_b'

If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.

main.py
my_list = [1, 2, 'a', 'b'] result = ''.join(map(str, my_list)) print(result) # 👉️ '12ab'
Use the search field on my Home Page to filter through my more than 3,000 articles.