为什么 str.format 会抛出一个 KeyError:对于这个看似简单的字符串格式化操作?



我写了下面的代码,与 f 字符串横向相比,无论我在哪里使用".format(("方法,我都会收到错误消息。错误消息是:

键错误: ' '

不知道为什么".format(("不像他的 f 字符串横向那样工作。如果没有,代码在使用".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))

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

根据.format年的文件,

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

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

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

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

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

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

{ }之间的额外空间是问题所在。

value = 123
print("{}".format(value))  # '123'
print("{ }".format(value))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
KeyError: ' '

在格式化字符串文本中,如果需要,可以在{ }中添加额外的空格。

value = 123
print(f"{value}")  # 123
print(f"{ value }")  # 123

最新更新