[英]KeyError python3.7
so I keep getting this error called : 所以我一直收到这个错误:
KeyError: 'width'
and I have no idea what to do, I defined what width
is, but it still doesn't work. 而且我不知道该怎么办,我定义了width
,但是仍然无法使用。
width = input("For how many characters do you want to align the table?")
then I convert it to an int
然后我将其转换为int
width = int(width)
line = ("| {:^{width}d} | {:^{width}b} | {:^{width}o} | {:^{width}x}")
print(line.format(1))
and when I try to run the programm I get an error. 当我尝试运行程序时,出现错误。
You have two problems: 您有两个问题:
width
needs to be passed as an argument to format
, which doesn't look for variables in the global scope. 需要将width
作为参数传递给format
,它不会在全局范围内查找变量。 1
as an argument for each unlabeled field in the string. 您需要为字符串中每个未标记的字段传递1
作为参数。 print(line.format(1, 1, 1, 1, width=width))
If you only want to provide 1
once, you need to modify your format string. 如果只想提供1
,则需要修改格式字符串。
# The leading 0 tells each specifier to take its value from the first
# positional argument to `format`.
line = "| {0:^{width}d} | {0:^{width}b} | {0:^{width}o} | {0:^{width}x}"
print(line.format(1, width=width))
它应该如下
print(line.format(1, 1, 1, 1, width=width))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.