String Formatting

Sort by

recency

|

1734 Discussions

|

  • + 0 comments

    It’s a great exercise for mastering alignment, spacing, and clean output formatting using f-strings, Cricbet99 login ID and Password

  • + 0 comments

    So, I love f-strings. This was the first time I've seen where something seemed a bit more hacky than with format strings, but I made it work. In particular, the start_pad bothers me, not sure why >{pad}d did not work.

    pad = len(bin(number)[2:])
    for i in range(1, number+1):
        start_pad = ' ' * (pad - len(str(i)))
        print(f"{start_pad}{i} {i:>{pad}o} {i:>{pad}X} {i:>{pad}b}")
    

    The [2:] is to strip the '0b' off the start of the return value from bin().

  • + 0 comments
    def print_formatted(number):
        # your code goes here
        bw = number.bit_length()
        for i in range(1, number+1):
            print("{0}".format(i).rjust(bw), "{0:o}".format(i).rjust(bw), "{0:X}".format(i).rjust(bw), "{0:b}".format(i).rjust(bw))
    
    ~
    
  • + 0 comments
    def print_formatted(number):
        width = len(f"{number:b}")
        for num in range(1,number+1):
            decimal = f"{num:d}".rjust(width)
            octal = f"{num:o}".rjust(width)
            hexa = f"{num:X}".rjust(width)
            binary = f"{num:b}".rjust(width)
            print(decimal, octal, hexa, binary)
    
  • + 0 comments
        width = len(bin(number)[2:])
        for i in range(1, number+1):
            print(
                str(i).rjust(width),
                oct(i)[2:].rjust(width),
                hex(i)[2:].upper().rjust(width),
                bin(i)[2:].rjust(width)
            )