python - 为什么 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))
解决方案
这绝对是一个错字,因为您在花括号中添加了空格。但是,我认为值得解释一下为什么会发生这种情况,所以你要小心不要犯同样的错误。
根据 中的文档.format
,
调用此方法的字符串可以包含由大括号 {} 分隔的文字文本或替换字段。每个替换字段都包含位置参数的数字索引或关键字参数的名称。
这意味着花括号内的任何内容都{}
将被解释为替换字段。在这种情况下,它是空间。
要了解这是如何工作的,您必须做一些奇怪的事情,例如将 kwargs 传递给format
:
>>> '{ }'.format(123)
KeyError: ' '
>>> '{ }'.format(**{' ': 123})
'123'
如果您只是省略了空格,这将是非常简单的文字插值。
>>> '{}'.format(123)
'123'
推荐阅读
- php - PHP - 字体回显问题
- php - Apache 和 IIS 之间的 PHP 脚本评估差异
- ubuntu - zfs ubuntu 18.04 上的 iozone 基准测试 - 错误:无法打开临时文件打开:无效参数
- apache - Apache 2.4.6 - ServerAlias 通配符,但 %1 未被替换
- scikit-learn - scikit-learn - 使用带有 RandomForestClassifier.predict() 的单个字符串?
- c# - 如何使用 API 在 Auth0 中验证以无密码身份验证发送的代码?
- sql - 使用声明的变量在 SQL Server 中运行演绎 CTE
- java - 如何通过 JNI 正确地将 std::map<> 从 C++ 发送到 Java?
- loops - Roblox Lua 中的褪色球
- mjml - MJML 运行并观察错误