Search code examples
pythonpython-3.xstring-formatting

How to format a string using variables instead of numbers within curly braces?


I'm using Python 3.7 and I have stored a value inside a variable. This variable holds the value of padding which I want to use within curly braces for string formatting. The code explains what I am trying to do.

def print_formatted(number):
    for i in range(1, number + 1):
        binum = bin(i).replace('0b', '')
        ocnum = oct(i).replace('0o', '')
        hexnum = hex(i).replace('0x', '')

        length = len(bin(number).replace('0b', ''))
        print('{0:>length} {1:>length} {2:>length} {3:>length}'.format(i, ocnum, hexnum, binum)) # Error here

This is the code that I have been trying to run. What I am trying to do is to right align the numbers by padding it by the value of the length of the last binary number.

ValueError: Invalid format specifier

This is the error I get. What am I doing wrong?


Solution

  • You can use f-strings and also format specifiers to avoid use of the hex, oct and bin builtins and then string slicing and use int.bit_length() instead of taking the length of the binary string, eg:

    def print_formatted(number):
        # get number of bits required to store number
        w = number.bit_length()
        for n in range(1, number + 1):
            # print each number as decimal, then octal, then hex, then binary with padding
            print(f'{n:>{w}} {n:>{w}o} {n:>{w}x} {n:>{w}b}')
    

    Running print_formatted(20) will give you:

        1     1     1     1
        2     2     2    10
        3     3     3    11
        4     4     4   100
        5     5     5   101
        6     6     6   110
        7     7     7   111
        8    10     8  1000
        9    11     9  1001
       10    12     a  1010
       11    13     b  1011
       12    14     c  1100
       13    15     d  1101
       14    16     e  1110
       15    17     f  1111
       16    20    10 10000
       17    21    11 10001
       18    22    12 10010
       19    23    13 10011
       20    24    14 10100