how to fix KeyError: 'w'. got it while doing string formatting in python

how to fix KeyError: 'w'. got it while doing string formatting in python

我正在尝试打印给定数字的十进制、八进制、十六进制和二进制表示形式,格式为:

number = int(input())
w = len('{0:b}'.format(number))
print("{0:{w}d} {0:{w}o} {0:{w}X} {0:{w}b}".format(number))

我期望的格式如下(比如输入 17):

17    21    11 10001

您需要为 format(value[, format_spec]) 使用 format_spec 关键字参数:

>>> print("{text}".format(text="hello"))

因此在你的情况下:

>>> number = 17
>>> w = len('{0:b}'.format(number))
>>> print("{0:{w}d} {0:{w}o} {0:{w}X} {0:{w}b}".format(number, w=w))

如果您希望在 {0} 占位符中替换 number 变量,在 {w} 占位符中替换 w 变量。

如果您搜索 "nesting":

,您可以在文档的 Format examples 中找到一个非常相似的示例

Nesting arguments and more complex examples:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'