"TypeError: can only join an iterable" when attempting to add list entries to a string

Viewed 13558

I have a class with two lists as variables. It has an object which is supposed to add every element in the lists to a (quite lengthy) string, which is then returned to the main program, to eventually by printed. I'm iterating through the list with a for-loop and using .join() to add every object to the string, but I'm getting a TypeError: "can only join an iterable".

The lists contain prices of what has been purchased in a restaurant, so just floating numbers.

Class A:

    def __init__(self, etc.):
        self.__foods = []
        self.__drinks = []

I then have an object which is supposed to print a receipt, with a predetermined form, which is then passed on to the main program as a string.

Class A:
    ...

    def create_receipt(self):
        food_price_string = "" # What is eventually joined to the main string
        food_prices = self.__foods # What is iterated

        for price in food_prices:
            food_price_string.join(price) # TypeError here
            food_price_string.join("\n")  # For the eventual print

Here's where I get the TypeError - the program refuses to join 'price' variable to the string created above. I'm supposed to do the same thing for the drink prices too, both of which would then be joined to the rest of the string:

1 Answers

There are two problems here:

  1. str.join does not alter the string (strings are immutable), it returns a new string; and
  2. it takes as input an iterable of strings that are joined together, not add a single string together.

The fact that food_prices is iterable does not matter, since you use a for loop, the prices are the element of the food_prices, and thus you join a single item of the list.

You can rewrite the program like:

def create_receipt(self):
    food_prices = self.__foods
    food_price_string = '\n'.join(str(price) for price in food_prices)
    food_price_string += '\n'  # (optional) add a new line at the end
    # ... continue processing food_price_string (or return it)
Related