Search code examples
pythonstring-formatting

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    21    11 10001

Solution

  • You need to use the format_spec keyword arguments for format(value[, 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.

    You can find a very similar example in the Format examples in the documentation if you search for "nesting":

    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'