首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将getattr与dict字符串格式化结合使用?

如何将getattr与dict字符串格式化结合使用?
EN

Stack Overflow用户
提问于 2018-07-03 04:27:29
回答 1查看 181关注 0票数 0

我有一个数据结构类和一个表格格式化类,我想在其中格式化一个文件并输出它。如果输出需要更改,我想要在飞行中创建格式化程序的灵活性。

class Row(object):
    __slots__ = ('date', 'item', 'expiration', 'price')
    def __init__(self, date, item, expiration, price=None):
        self.date = date
        self.item = item
        self.expiration = expiration
        self.price = ""

        if price:
            self.price = price

class Formatter(object):
    def row(self, rowdata):
        for item in rowdata:
            print('<obj date="{date}" item="{item}" exp="{expiration}" price="{price}" />\n').format(**item)


def print_table(objects, colnames, formatter):
    for obj in objects:
        rowdata = [str(getattr(obj, colname)) for colname in colnames]
        formatter.row(rowdata)

我这样叫它:

data = [Row("20180101", "Apples", "20180201", 1.50),
         Row("20180101", "Pears", "20180201", 1.25)]

formatter = Formatter()
print_table(data, ['date','item','expiration','price'], formatter)

我期望看到的是:

<obj date="20180101" item="Apples" exp="20180201" price="1.50" /> <obj date="20180101" item="Pears" exp="20180201" price="1.25" />

我当前收到以下错误:TypeError: format() argument after ** must be a mapping, not str

有人能帮上忙吗?谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-07-03 04:36:00

**item无效,因为**运算符要求命名的变量是字典(映射),而您尚未提供该值(item是字符串)。因此,您需要将item转换为字典,并在format语句中使用正确的键/值对。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51143317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档