Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Daniil Silantev
The Python "TypeError: sequence item 0: expected str instance, float found"
occurs when we call the join()
method with an iterable that contains one or
more floats. To solve the error, use the map()
function to convert all items
in the iterable to strings before calling join
.
Here is an example of how the error occurs.
my_list = [1.1, 2.2, 'a', 'b'] # ⛔️ TypeError: sequence item 0: expected str instance, float 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 the map()
function to convert all values
in the iterable to strings.
my_list = [1.1, 2.2, 'a', 'b'] result = ''.join(map(str, my_list)) print(result) # 👉️ "1.12.2ab"
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
str()
class with each item in the iterable to convert them to strings before using the join()
method.An alternative and more explicit approach is to use a generator expression.
my_list = [1.1, 2.2, 'a', 'b'] result = ''.join(str(item) for item in my_list) print(result) # 👉️ "1.12.2ab"
Generator expressions and list comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
We used a generator expression to convert each item to a string by passing it to
the str()
class.
You can also use a list comprehension by wrapping the expression in square brackets.
my_list = [1.1, 2.2, 'a', 'b'] result = ''.join([str(item) for item in my_list]) print(result) # 👉️ "1.12.2ab"
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.
my_list = [1.1, 2.2, 'a', 'b'] result = '_'.join([str(item) for item in my_list]) print(result) # 👉️ "1.1_2.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.
my_list = [1.1, 2.2, 'a', 'b'] result = ''.join([str(item) for item in my_list]) print(result) # 👉️ "1.12.2ab"