String Formatting

  • + 19 comments

    I solved it similarly but thought it was more readable to just substring each one e.g.,

    b = str(bin(i))[2:]
    

    My rjust calls are a little less readable if someone hasn't used exploding args before, but I really didn't want to write it more than once.

    n = int(input())
    
    results = []
    
    for i in range(1, n+1):
        decimal = str(i)
        octal = str(oct(i)[2:])
        hex_ = str(hex(i)[2:]).upper()
        binary = str(bin(i)[2:])
    
        results.append([decimal, octal, hex_, binary])
    
    width = len(results[-1][3])  # largest binary number
    
    for i in results:
        print(*(rep.rjust(width) for rep in i))
    

    Note: Python 3.