小编0x3*_*x32的帖子

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

我有一个带有两个列表作为变量的类。它有一个对象,该对象应该将列表中的每个元素添加到一个(很长的)字符串中,然后返回到主程序,最终通过打印。我正在使用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'变量连接到上面创建的字符串。我也应该对饮料价格做同样的事情,然后将两者都加入到字符串的其余部分中:

python join list object python-3.x

2
推荐指数
1
解决办法
7376
查看次数

标签 统计

join ×1

list ×1

object ×1

python ×1

python-3.x ×1