Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Jonatan Pie
The Python "TypeError: sequence item 0: expected str instance, bool found"
occurs when we call the join()
method with an iterable that contains one or
more None
values. To solve the error, figure out where the None
values come
from or filter them out before calling join
.
Here is an example of how the error occurs.
my_list = [None, None, 'a', 'b'] # ⛔️ TypeError: sequence item 0: expected str instance, NoneType found result = ''.join(my_list)
The join
method raises a TypeError
if there are any non-string values in the
iterable.
None
values in the iterable came from and correct the assignment.The most common sources of None
values are:
None
implicitly).None
.If you want to filter out the None
values from the iterable, use the
filter()
function.
my_list = [None, None, 'a', 'b'] result = ''.join(filter(lambda x: x if x is not None else '', my_list)) print(result) # 👉️ 'ab'
If your iterable contains other values that are not of type string, make sure to
pass them to the str()
class to convert them to strings before passing them to
join()
.
my_list = [None, None, 'a', 'b'] result = ''.join(filter(lambda x: str(x) if x is not None else '', my_list)) print(result) # 👉️ 'ab'
The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
If you pass None
for the function argument, all falsy elements of the iterable
are removed.
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
TypeError
if there are any non-string values in the iterable.If your list contains numbers, or other types, convert all of the values to
string before calling join()
.
my_list = ['a', 'b', 1, 2] all_strings = list(map(str, my_list)) print(all_strings) # 👉️ ['a', 'b', '1', '2'] result = ''.join(all_strings) print(result) # 👉️ "ab12"
The string the method is called on is used as the separator between elements.
my_list = ['a', 'b', 'c'] my_str = '-'.join(my_list) print(my_str) # 👉️ "a-b-c"
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.
my_list = ['a', 'b', 'c'] my_str = ''.join(my_list) print(my_str) # 👉️ "abc"