首页 > 解决方案 > 为什么 str.format 会为这个看似简单的字符串格式化操作抛出 KeyError: ' ' ?

问题描述

我编写了下面的代码,与 f-string 横向相比,无论我在哪里使用“.format()”方法,都会收到一条错误消息。错误信息是:

键错误:“”

不知道为什么“.format()”不像他的 f-string 横向那样工作。如果没有,代码在使用“.format”的区域运行得很好

你能指出我正确的方向吗?非常感激!


class Inventory ():

    make = "Verra"

    def __init__ (self,country,isnew,sbalance = 0,cbalance = 0):

        self.country = country
        self.isnew = isnew
        self.cbalance = cbalance
        self.sbalance = sbalance



    def entry_sugar (self,sugar_1 = 0):

        self.sbalance += sugar_1

        print(f"You have just added {sugar_1} bags of sugar to your sugar 
        inventory")

        print(f"Your new sugar inventory balance is : {self.sbalance} bags.")



    def entry_corn (self,corn_1 = 0):

        self.cbalance += corn_1

        print(f"You have just added {corn_1} corn(s) to your corn inventory.")

        print(f"Your new corn inventory balance is : {self.cbalance}.")




    def withdawal_sugar(self,sugar_2 = 0):

        if self.sbalance == 0:

            print("Your current sugar inventory is at 0.You cannot withdraw an 
            item at this time")

        else:

            self.sbalance = self.sbalance - sugar_2

            print("You have just withdrawned { } bags of sugar from your sugar 
            inventory".format(sugar_2))

            print(f"Your new sugar inventory balance is : {self.sbalance} bags 
            of sugar.")



    def withdawal_corn(self,corn_2 = 0):

        if self.cbalance == 0:

            print("Your current corn inventory is at 0.You cannot withdraw an 
            item at this time")

        else:

            self.cbalance = self.cbalance - corn_2

            print(f"You have just withdrawned {corn_2} corn(s) from your corn 
            inventory")

            print(f"Your new corn inventory balance is : {self.cbalance}")


    def total_balance (self):

        print("Balance Summary:")     
        print("Your corn balance is {}".format(self.cbalance))
        print("Your sugar balance at this time is{}".format(self.sbalance))


标签: pythonformat

解决方案


这绝对是一个错字,因为您在花括号中添加了空格。但是,我认为值得解释一下为什么会发生这种情况,所以你要小心不要犯同样的错误。

根据 中的文档.format

调用此方法的字符串可以包含由大括号 {} 分隔的文字文本或替换字段。每个替换字段都包含位置参数的数字索引或关键字参数的名称。

这意味着花括号内的任何内容都{}将被解释为替换字段。在这种情况下,它是空间。

要了解这是如何工作的,您必须做一些奇怪的事情,例如将 kwargs 传递给format

>>> '{ }'.format(123)
KeyError: ' '
>>> '{ }'.format(**{' ': 123})
'123'

如果您只是省略了空格,这将是非常简单的文字插值。

>>> '{}'.format(123)
'123'

推荐阅读