简体   繁体   English

如何修复KeyError:'w'。 在python中进行字符串格式化时得到了它

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

I am trying to print the decimal, octal, hex and binary representation of a given number with format : 我正在尝试使用格式打印给定数字的十进制,八进制,十六进制和二进制表示形式:

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

The format that I am expecting is as below (say for input 17): 我期望的格式如下(输入17所示):

17    21    11 10001

You need to use the format_spec keyword arguments for format(value[, format_spec]) : 您需要为format(value[, format_spec])使用format_spec关键字参数:

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

Therefore in your case: 因此,在您的情况下:

>>> 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))

if you want number variable to be replaced in the {0} placeholder and w variable in {w} placeholder. 如果要在{0}占位符中替换number变量,而在{w}占位符中替换w变量。

You can find a very similar example in the Format examples in the documentation if you search for "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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM