Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Vitaly Otinov
The Python "TypeError: sequence item 0: expected str instance, tuple found"
occurs when we call the join()
method with an iterable that contains one or
more tuples. To solve the error, use a nested join()
to join the elements of
each tuple.
Here is an example of how the error occurs.
my_list = [('a', 'b'), ('c', 'd'), ('e', 'f')] # ⛔️ TypeError: sequence item 0: expected str instance, tuple found result = ''.join(my_list)
The join
method raises a TypeError
if there are any non-string values in the
iterable.
One way to solve the error is to use a generator expression with a nested
join()
.
my_list = [('a', 'b'), ('c', 'd'), ('e', 'f')] result = ''.join(''.join(tup) for tup in my_list) print(result) # 👉️ 'abcdef'
We called the join()
method with each tuple in the list and then joined the
strings.
If your tuple might contain non-string values, you'll have to convert each value to a string.
my_list = [(1, 2), 'c', 'd', 'e', 'f'] result = ''.join(''.join(map(str, tup)) for tup in my_list) print(result) # 👉️ '12cdef'
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
If you want to join the tuples into a string, you can pass each tuple to the
str()
class.
my_list = [('a', 'b'), ('c', 'd'), ('e', 'f')] result = ''.join(str(tup) for tup in my_list) print(result) # 👉️ "('a', 'b')('c', 'd')('e', 'f')"
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorThe 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"