尝试将列表项添加到字符串中时出现“ TypeError:只能加入可迭代对象”

0x3*_*x32 2 python join list object python-3.x

我有一个带有两个列表作为变量的类。它有一个对象,该对象应该将列表中的每个元素添加到一个(很长的)字符串中,然后返回到主程序,最终通过打印。我正在使用for循环遍历列表,并使用.join()将每个对象添加到字符串中,但是却遇到TypeError:“只能加入可迭代对象”。

清单中包含在餐厅购买的商品的价格,因此仅包含浮动数字。

Class A:

    def __init__(self, etc.):
        self.__foods = []
        self.__drinks = []
Run Code Online (Sandbox Code Playgroud)

然后,我有一个对象,该对象应该以预定格式打印收据,然后将其作为字符串传递给主程序。

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
Run Code Online (Sandbox Code Playgroud)

这是我收到TypeError的地方-程序拒绝将'price'变量连接到上面创建的字符串。我也应该对饮料价格做同样的事情,然后将两者都加入到字符串的其余部分中:

Wil*_*sem 5

这里有两个问题:

  1. str.join 不更改字符串(字符串是不可变的),它返回一个新字符串;和
  2. 它以连接在一起的可迭代字符串作为输入,而不是将单个字符串添加在一起。

food_prices可迭代的事实无关紧要,因为您使用for循环,所以prices是的元素food_prices,因此您可以连接列表的单个项目。

您可以像这样重写程序:

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)
Run Code Online (Sandbox Code Playgroud)