我们可以在字典中使用字符串格式化吗?这是我的代码要求-在花括号的位置,我想使用存储在变量invoice id中的任何值。如何在字典中传递该值
INVOICE_NOT_EXIST = {'invoice': 'object with id={} does not exist.'}
invoice_id = 5214
detail={INVOICE_NOT_EXIST}
# detail={INVOICE_NOT_EXIST}.format(invoice_id) # this is an error as we know 'dict' object has no attribute 'format'
如果我这样做,那么它是设置的,但我的要求是字典。
INVOICE_NOT_EXIST = "'invoice': 'object with id={} does not exist.'"
invoice_id = 5214
detail={INVOICE_NOT_EXIST.format(invoice_id)}
有办法......可以满足我的要求。
你可以试试:
INVOICE_NOT_EXIST = {'invoice': 'object with id={} does not exist.'}
invoice_id = 5214
detail = INVOICE_NOT_EXIST['invoice'].replace("{}", invoice_id)
输出:
>>> print(detail)
object with id=5214 does not exist.
但是,我认为你应该改变处理这些错误的方式。