String Formatting

Sort by

recency

|

1759 Discussions

|

  • + 0 comments
        w = int(math.log(n,2))+1
        for i in range(1,n+1):
            print("{0:{1}d} {0:{1}o} {0:{1}X} {0:{1}b}".format(i,w))
    

    I thought it simplest to just calculate the length of the binary representation.

    Note how {0: specifies the first positional argument, and {1} specifies the second for width.

  • + 0 comments

    def print_formatted(number): # your code goes here width = len(bin(number)[2:]) for i in range(1, n+1): print(str(i).rjust(width), end =' ') print(oct(i)[2:].rjust(width), end =' ') print(hex(i)[2:].rjust(width).upper(), end =' ') print(bin(i)[2:].rjust(width), end =' ') print()

    if name == 'main': n = int(input()) print_formatted(n)

  • + 0 comments

    Here is String formatting problem solution in python 2 and python 3 -https://programmingoneonone.com/hackerrank-string-formatting-solution-in-python.html

  • + 0 comments

    Determine max width (binary of n) → Loop through numbers → Convert to all bases → Align right → Print in one row.

    def print_formatted(number):

    width=len(bin(number)[2:])
    
    for i in range (1,number+1):
    
        decimal=str(i)
    
        octal=oct(i)[2:]
    
        hexa=hex(i)[2:].upper()
    
        binary=bin(i)[2:]
    
        print(decimal.rjust(width),
        octal.rjust(width),hexa.rjust(width),binary.rjust(width))
    
  • + 0 comments
    def print_formatted(number):
        number_bin = f"{number:b}"
        width = len(number_bin)
        for i in range(1, number + 1):
            result = f"{i}".rjust(width)+ " " + f"{i:o}".rjust(width) + " " + f"{i:X}".rjust(width)+ " " + f"{i:b}".rjust(width)
            print(result)
    if __name__ == '__main__':
        n = int(input())
        print_formatted(n)