String Formatting

  • + 89 comments

    This is all about formatting so...

    n = int(raw_input())
    width = len("{0:b}".format(n))
    for i in xrange(1,n+1):
      print "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width)
    
    • + 2 comments
      [deleted]
      • + 4 comments

        here is python problem solution https://programs.programmingoneonone.com/2021/01/hackerrank-string-formatting-solution-python.html

        • + 15 comments

          can you explain why there is '-2' in width = len(bin(N)) - 2?

          isnt it supposed to be the length of the binary value? I am confused why subtracting 2 from the lenth works

          I myself actually don't understand what the requirement is asking...about the width should be equal to the binary value. can anyone explain? thankyou.

          • + 0 comments

            because bin(N) also contain 0b as prefix

          • + 0 comments

            eliminates the spaces in your output

          • + 0 comments

            bin() returns binary value with 'ob' appended in front of it. For example- binary value of 344 is 101011000, but bin(344) returns 0b101011000. Notice the ob in front of it, ob denotes binary, similarly for octal it's 'oo' and for hexadecimal it is 'ox' that's why we need -2 to find length of binary.

          • + 0 comments

            samuel , actually bin(2) is "0b10" bin(7) is "0b111" and so on the compiler gives the output in "0b____" so the length of any binary number will be of actual length + 2 thats why we subtract 2 from actual length we can also write the same code: width=len(bin(n)[2:])

          • + 0 comments

            To reduce space between outputs as show in test case output

          • + 1 comment

            could you get the answer?....len(bin(N))-2? if yes then please explain me!!!

            • + 0 comments

              Yep! it worked for me and please refer to yaswanthpalika(my above comment thread) for detailed answer, thank you

          • + 0 comments

            I haven't checked the solution above, but It's because when you use bin() it returns with the prefix '0b' e.g len(bin(6)) -> len('0b110')

          • + 0 comments

            bin(2)='0b10' bin(5)='0b101' hence to get actual length of binary digit ,subtract 2(i.e '0b') from length of string( i.e len(bin(n)) Hope you understand.

          • + 0 comments

            because it has 0b before any binary number, so you need to take those two from the length

          • + 0 comments

            bin(10) returns 0b10 whereas what you want is 10 . The 0b is the representation that the number is a binary and is the same for 0x(for hex) and 0o (for octal). So when formating it we need to -2 from the length to properly format the string.

          • + 0 comments

            Binary numbers are expressed in python as "0bx", where x is the number. So 10010 would be "0b10010". This is so the interpreter can tell which base the number is in. There's also 0hx and 0ox for hexadecimal and octal numbers. So the length of bin(n) is actually 2 characters longer than the length of the number itself.

          • + 0 comments

            because if we use bin(n) we also get two additional numbers or charaters like 00xxxxxx so two remove this from the length we use -2

          • + 0 comments

            -2 is done because when you convert any number to binary it returns a string in which the first two letters just represent that it is binary so that is useless and needed to be removed ex : bin(10) = "0b1010" so the first two letters "0b" represent that the number is in binary

          • + 1 comment

            you can simply use len(format(n,'b')) if u dont want to use -2

            • + 0 comments

              very True

          • + 0 comments

            because the function bin(number) returns a string starting with "ob" which should be neglected when counting the length of the binary equvivalent of the number

        • + 8 comments

          what is d,o,X,b ?? i couldnt understand that part. Can you please tell me in detail?

          • + 0 comments

            It looks like it forces the number to d(ecimal), o(ctal), (he)X and b(inary).

          • + 0 comments

            decimal octal hexadecimal and binary

          • + 0 comments

            d for decimal o for octal x for hexa decimal b for binary it is a format() parameters you can see more at 'https://www.w3schools.com/python/ref_func_format.asp'

          • + 0 comments

            d tells that the number is decimal o stands for octal x for hexadecimal and b for binary 0 is just for telling the format. Simple :)

          • + 0 comments

            D stands for decimal, O stands for octal, X stands for Hexadecimal, b for binary, hope you understood

          • + 0 comments

            decimal, oct, hex, binary

          • + 0 comments

            d to convert a number into decimal value o to convert a number into octal value X to convert a number into capital hexadecimal value b to convert a number into binary value

        • + 3 comments

          Updated solution is here

          https://www.thecscience.com/2021/06/HackerRank-string-formatting-in-python-problem-solution.html

          • + 0 comments

            pls dont post soultion people dont learn then idiot

          • + 0 comments

            stop putting soultion u moron

          • + 0 comments

            frick u

        • + 0 comments

          Can someone please explain why hackerrank rejected my solution for every test case except test case 0? here is the code:

          def setw(n):
              s = ''
              for i in range(n):
                  s += ' '
              return s
          
          def print_formatted(number):
              # your code goes here
              b = len(str(bin(number)[2:]))
              for i in range(1, number+1):
                  print(setw(b-len(str(i))), i,' ', setw(b-len(str(oct(i)[2:]))), oct(i)[2:], ' ', setw(b-len(str(hex(i)[2:]))), hex(i)[2:], ' ', setw(b-len(str(bin(i)[2:]))), bin(i)[2:], sep='')
          
          if __name__ == '__main__':
              n = int(input())
              print_formatted(n)
          

          The code outputs the exact same digits at the exact same position but hackerrank is not accepting it.

      • + 2 comments

        can u pls explain y we have taken len("{0:b}".format(n)) overthere? pls explain total program if possible

        • + 3 comments

          can u please tell me what is xrange?

          • + 0 comments

            backwards i think so if your doing from 1 to 10, with xrange it will be from 10 to 1

          • + 2 comments
            [deleted]
            • + 0 comments

              i deleted it accidently, so xrange is backwards, so if the range was from 1 to 10, with xrange it would be 10 to 1.

            • + 1 comment

              xrange atually means to do it double the times you make it do

              • + 1 comment

                thats my brother trying to trick you, he lies

                • + 1 comment

                  cap

                  • + 1 comment

                    stop, i'm trying to help someone!

                    • + 1 comment

                      stop the cap hes lying and hes not my brother i reproted him

                      • + 1 comment

                        stop

                        • + 0 comments

                          you both are wrong. xrange prints given number of xmas trees in the output. dumbasses

          • + 1 comment

            The xrange() function in Python is used as similar to the range() function. However, xrange() is used only in Python 2. x whereas range() is used in Python 3. x.

            • + 0 comments

              and also a return type is different from xrange() and range(). range()-This returns a range object (a type of iterable). xrange()-This function returns the generator object that can be used to display numbers only by looping.

        • + 0 comments

          Easy Sol. -- https://codecracksol.blogspot.com/2022/03/string-formatting.html

    • + 6 comments

      can you please explain this format() function?? --a beginner

      • + 8 comments

        please do refer this https://pyformat.info/

        • + 0 comments

          Thank you..

        • + 0 comments

          awesome resorce thank you for sharing!

        • + 0 comments

          Great fresource for beginners!

        • + 0 comments

          Realy It's help full

        • + 0 comments

          Nice reference bro

        • + 0 comments

          thanks

        • + 0 comments

          Thank u for sharing ...was very helpful.

        • + 1 comment

          can we know if there any similar sites for other topics too in python thanks in advance bro

          • + 0 comments

            https://data-flair.training/blogs/python-tutorials-home/

      • + 36 comments

        You could use this...:

        from future import print_function

        st=int(raw_input())

        w=len(bin(st)[2:])

        for i in range(1,st+1):

        print (str(i).rjust(w,' '),str(oct(i)[1:]).rjust(w,' '),str(hex(i)[2:].upper()).rjust(w,' '),str(bin(i)[2:]).rjust(w,' '),sep=' ')
        
        • + 0 comments

          This is a method that we are more familiar

        • + 3 comments

          bin(i)[2:] is a string already, no need to converte again.

          • + 0 comments

            yeah.. thats right

          • + 1 comment

            are hex,oct and bin always strings?

            • + 0 comments

              Yes

        • + 7 comments

          Could you explain the line

          w=len(bin(st)[2:])
          
          • + 1 comment

            This line of code responses to this requirement: "Each value should be space-padded to match the width of the binary value of n."

            • + 1 comment

              but why widhth for every value is len of binary value?

              • + 0 comments

                because the challenge want us to do so

                Each value should be space-padded to match the width of the binary value of number and the values should be separated by a single space

          • + 0 comments

            this is string slicing. bin function return string. str="abcd" then output of str[2:] is cd.

          • + 0 comments

            taking the value from 2 digit so it can ignore 0x

          • + 0 comments

            when we use bin() method, it returns binary value but it starts with 0b. For example : bin(1) = 0b1, so to remove '0b' from the beginning we use string slicing.

          • + 0 comments

            See the python documentation for the bin() function.

            "converts an integer number to a binary string prefixed with 0b"

          • + 0 comments

            converting the st into binary and then slicing it mean it will take values from the 2 index. and then taking the length of it and storing it in w.

          • + 0 comments

            the 2: removes the 0o stuff person from 5 years ago

        • + 3 comments
          str(oct(i)[1:]).rjust(w,' ')
          

          should be

          str(oct(i)[2:]).rjust(w,' ')
          

          Otherwise, we have an "o" before the octal answer.

          • + 2 comments

            can u pls tell me how rjust(w,' ') works??

            • + 1 comment

              You can refer to the previous challenge. Basically it means adjusting to the right with width w and empty space filled with whitespace ie. ('').

              • + 1 comment

                is it necessary to specify the whitespace padding?? isn't it the defaut valu???

                • + 0 comments

                  It isn't necessary. Default is white space

            • + 2 comments

              i am your yur big fan #Golmal series when did you start coading huh ?

              • + 0 comments

                6 years ago

              • + 1 comment

                hahahaaaa.....

                • + 0 comments

                  hahaha

          • + 0 comments

            "o" is in Python 3, in Python 2 there is only a zero

          • + 0 comments

            actually its 0o,so using[2:] will do

        • + 1 comment

          plz explane this line : w=len(bin(st)[2:]) why u use [2:] and also use of sep=' '

          • + 2 comments

            1.

            bin(5) returns 0x101

            bin(15) returns 0x1111

            To remove the '0x' part we use [2:]

            2.

            sep=' ' is used like below

            print("x","y","z",sep=',') ==> x,y,z

            print("x","y","z",sep='|') ==> x|y|z

            i hope this helps.

            • + 8 comments

              Hey please help me out. I have tried this on terminal and it works perfectly. I don't know why is it not passing through the test cases here:

              from __future__ import print_function
              def print_formatted(n):
              # your code goes here
              for i in range(1, n+1):    
                  print (' ' + (str(i).rjust(len(str(i))).rjust((len(str(n))), ' ')) + (str(oct(i))[1:].rjust(len(str(bin(n))[2:])+1)) + ((str(hex(i))[2:].upper()).rjust(len(str(bin(n))[2:])+1)) + (str(bin(i))[2:].upper().rjust(len(str(bin(n))[2:])+1)))
              
              • + 0 comments

                I am not sure if we can import modules.

                if it is not passing, that means

                from __future__ import print_function
                

                not working here

              • + 0 comments

                same here: def print_formatted(n): power = 0 while 2**power <= number: power += 1 power += 1 for i in range(1,number+1): print(str(i).rjust(power, ' ')+format(i,'o').rjust(power, ' ')+format(i, 'X').rjust(power, ' ')+format(i, 'b').rjust(power, ' '))

              • + 0 comments

                printing one extra line same as my code def print_formatted(number): # your code goes here for i in range(number): print(str(i+1)+" "+str(oct(i+1))[2:len(str(oct(i+1)))]+" "+str(hex(i+1))[2:len(str(hex(i+1)))]+" "+str(bin(i+1))[2:len(str(bin(i+1)))])

              • + 0 comments

                same problem here

              • + 0 comments

                replace str(oct(i))[1:] with replace str(oct(i))[2:]

              • + 0 comments

                Remove the first space " " in print and use rjust(len(str(bin(number)[2:]))) The below code works perfectly def print_formatted(number):

                for i in range(1,number+1):
                    print(str(i).rjust(len(str(bin(number)[2:])))+" "+str(oct(i)[2:]).rjust(len(str(bin(number)[2:])))+" "+str(hex(i)[2:]).upper().rjust(len(str(bin(number)[2:])))+" "+str(bin(i)[2:]).rjust(len(str(bin(number)[2:]))))
                
              • + 0 comments

                why are we using width as len(str(bin(n)) in every case??

            • + 0 comments

              surely bin(5) returns 0b101

        • + 0 comments

          how this rjust() works

        • + 1 comment

          why upper() is used?

          • + 0 comments

            because the question asks to print capital hexadecimal equivalents

        • + 1 comment

          I used same method and on the pycharm I get same output, however I could not submit hear :(

          • + 0 comments

            i=1 while i<=number: print(i, end=' ') print(oct(i)[2:],end=' ') print(hex(i)[2:],end=' ') print(bin(i)[2:]) i += 1

            Got same output here too still not submitted here.

        • + 0 comments

          rjust(w,' ') space not needed herer as it is taken by default

        • + 1 comment

          Sorry I am a beginner, may I know what [1:] does in the str function str(oct(i)[1:]) ?

          • + 1 comment

            https://developers.google.com/edu/python/strings#string-slices You need not apologise for asking doubts even rank no 1 in python didnt know this when he started learning python. The link pasted above answers your doubt the same link can be used to get started with python programming.Good luck :)

            • + 0 comments

              Thanks a lot :)

        • + 1 comment

          It could be just : w = st.byte_length()

          • + 0 comments

            Found this comment. Suprised no one was giving an up. Smart use of count, though I have to use bit_length() instead.

        • + 0 comments

          The output for the oct for some reason has the letter 'o' adjacent to it, what is thre potential cause?

          1 o1 1 1 2 o2 2 10

        • + 0 comments

          correction: str(oct(i)[2:]) instead of str(oct(i)[1:])

        • + 0 comments

          Thanks a lot. I was doing the rjust thing wrong before going through your solution.

          It worked without the sep = ' '

        • + 0 comments

          why have you used //str(hex(i)[2:].upper()).rjust(w,' ')// I'mma noob

        • + 0 comments

          why does it fail some of the test cases?

        • + 0 comments

          n=int(input()) i=1 while i<=n: print(i, oct(i).lstrip('0o'), hex(i).lstrip('0x').upper(), bin(i).lstrip('0b')) i=i+1

              is this is valid..because it is showing the same result..but ub=nable to pass all test case
          
        • + 0 comments

          don't use sep=' ' as we are already ussing space as a filler.

        • + 0 comments

          str(hex(i)[2:].upper()) why we are converting into upper

        • + 0 comments

          please make a correct ..it will be str(oct(i)[2:]).rjust(w,' ') thanks for the code

        • + 0 comments

          Easy to understand for a begineer . Thank You !

        • + 0 comments

          why we can't use "+" sign instead of " , "

        • + 0 comments

          why did you took the substring from 2 ?

        • + 0 comments

          use str(oct(i)[2:]).rjust(w,' ') instead of str(oct(i)[1:]).rjust(w,' ').Thanks for ur code...

        • + 0 comments

          This code is not giving the required output .

        • + 0 comments

          We need to find the width of number (i.e. the greatest number) entered by user for finding each decimal, octal, haxadecimal and binary equivalent so, that every number gets right shifted accordingly in each iteration for all the formats, not just by calculating width in binary format.

        • + 0 comments

          Thank you! Super helpful.

          Small sidenote: the deafult for the sep parameter in the print function is a spcae, so no need to use it here.

        • + 0 comments
          nm = int(input())
          [i for i in range(1, nm +1) if print(str(f"{i:{len(bin(nm)[2:])}d} {i:{len(bin(nm)[2:])}o} {i:{len(bin(nm)[2:])}X} {i:{len(bin(nm)[2:])}b}"))]
          
        • + 1 comment

          in w=len(bin(st)[2:]) why did u took [2:] in the statement?

          • + 0 comments

            for example bin(5) gives '0b101' here actual bineary representation starts at index 2 . so bin(5)[2:]='101' len(bin(5)[2:])=3 hope this clarifies your doubt.

        • + 0 comments

          Thank you

        • + 0 comments

          No need to use pass the parameter sep=" ", given that it is already set by default as ' '.

        • + 0 comments

          why rjust(w,' ')?

        • + 0 comments
          def print_formatted(number):
                  len_b = len(f'{number:b}')
                  for i in range(1,number+1):
                      print(f'{i:d}'.rjust(len_b), f'{i:o}'.rjust(len_b), f'{i:X}'.rjust(len_b), f'{i:b}'.rjust(len_b), end='\n') 
          

          This is what I got

        • + 0 comments

          It should be str(oct(i)[2:]), since the oct() function always returns '0o' before the base-8 number

      • + 1 comment
        # In the most basic way, this is what format() does
        >>> x = "replaced"
        >>> "This is {}!".format(x)
        'This is replaced!'
        
        • + 0 comments

          good one

      • + 0 comments

        what is the function of 0 before :{width}, why it is not working without 0. For printing only deciaml it does print but its not working with binary, octa , he and decmal

      • + 0 comments

        str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.\ Ex:: print ("{}, A computer science portal for geeks." .format("GeeksforGeeks"))

        str = "This article is written in {}" print (str.format("Python"))

        print ("Hello, I am {} years old !".format(18))

      • + 0 comments

        format() is used to show effect like formate string with amazing power a=2 b=3 sum=a+b print("sum of {} and {} is {}".format(a,b,sum)) output:-sum of 2 and 3 is 5 another power: print("sum of {1} and {0} is {2}".format(a,b,sum)) output:-sum of 3 and 2 is 5

    • + 0 comments

      that's straight up witchcraft what you did there

    • + 0 comments

      This is a new way of formatting. So many new things to learn :-o

    • [deleted]
      + 1 comment

      To get the number of bits of n, why isn't len("{0:{0}b}".format(n)) working?

      • + 1 comment

        The {0} part does a right justification with n inside format. Hopefully this explains what I mean a bit more (did this in a Python 3.5 interpreter on Windows 10):

        >>> n = 17
        >>> "{0:{0}b}".format(n)
        '            10001'
        >>> len("{0:{0}b}".format(n))
        17
        >>>
        
        • + 0 comments

          for more reference https://www.geeksforgeeks.org/python-format-function/

    • + 1 comment

      What is the importance of width=width?

      • + 2 comments

        Without width=width, the code would not run (as format would have no idea what {width} should be set to.

        If you're asking what it does, then it tells the format function to set all {width} parts parameter to the width variable defined at line 2.

        If you're asking why {width} is there, then it tells format to space out the output of each number to the largest number string (which is found out by line 2 of the code).

        • + 0 comments

          Still a little unclear - why would it have to tell the format function to set width to the width at line 2?

          It seems like width is being assigned twice here. First at line 2. width = len("{0:b}".format(n))

          Then in the format function. width=width

          Doesn't width by itself already refer to the assignment done in line 2?

        • + 1 comment

          Put in another way, how does format have no idea what width should be set to? Isn't width set in line 2 already?

          • + 1 comment

            It's because they're two different variables. width in line 2 belongs to the user program, while the other width belongs to the format function (noted by {width}).

            Although not exactly the same, a similar example would be a variable defined in a function versus after (and outside of) one:

            def func(x):
                return x + x
            
            x = 12
            func()
            

            Which returns the following:

            Traceback (most recent call last):
              File "<stdin>", line 5, in <module>
            TypeError: func() missing 1 required positional argument: 'x'
            
            • + 0 comments

              def func(x): return x + x

              x = 12 print(func(x))

    • + 0 comments

      will you please explain.

    • + 1 comment

      can you please explane the use of width and with=width

      • + 4 comments

        don't think the line width = width

        change the code to

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

          thanks that worked for me in python 2

        • + 1 comment

          Not working for Python 3

          • + 2 comments

            it's working, write this.

            def print_formated(n): w = len("{0:b}".format(n)) for i in range(1,n+1): print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=w)) if name=='main': n=int(input()) print_formated(n)

            • + 0 comments

              Can you please explain?

        • + 1 comment

          can you explain wht is w?? i mean how it works??

          • + 0 comments

            Let's first look at what w is.

            w = len("{0:b}".format(n))

            The question asked to format each value to the width of the binary of the number, which is {0:b}.format(n). For example, decimal 17 would be 10001. Converting this value to string gives a 5 character-long string, which you can apply to the width parameter of format( ).

    • [deleted]
      + 1 comment

      what's wrong with this. n = int(input()) for i in range(1,n+1): print ("{0:d} {0:o} {0:X} {0:b}".format(i))

    • + 2 comments

      Can you please explain this line. Thanks

      print {0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width)
      
      • + 0 comments

        "{0:{width}d}" Explained--> "0" --> for index in "format(i, width=width)". It takes the 'ith'value. "{width}d" --> converts the width into decimal. Refer "Padding numbers" in https://pyformat.info/

      • + 0 comments

        print("{0} {1} {0} ". format("hi", 567)) outputs => hi 567 hi

        0=> hi 1=> 567 similarly {0:{1}d}.format(i, width) is equal to {0:4d} where width is 4. if i=56, above formatting givs output _ _5 6 ## space denoted by _ for understanding

    • + 1 comment

      why this

      "{0:b}"
      
      • + 0 comments

        "{0:{width}d}" Explained--> "0" --> for index in "format(i, width=width)". It takes the 'ith'value. "{width}d" --> converts the width into decimal. Refer "Padding numbers" in https://pyformat.info/

    • + 0 comments

      Please elaborate this width function in detail

    • + 0 comments

      Well done, I couldnt get the proper framing of this, this is VERY VERY clear and well done

    • + 0 comments

      Thank you it works..but can u elaborate what you have done or the concept???

    • + 0 comments

      I tried this method but its showing "Unknown format code 'w' for object of type 'int'"

    • + 0 comments

      Can you explain your code

    • + 0 comments

      width = len("{0:b}".format(n)) what does this line do? -a Beginner

    • + 1 comment

      {0:{width}d} what does 0 here denote?

      • + 1 comment

        He's referring to the 0 position argument in format(), this can be very useful, however is mostly left out from simple formatting to not clutter the code.

        See this formatting scenario:

        print('{} dog barks at {}!'.format('His', 'night'))
        

        since 2 arguments are supplied and 2 spots are available to be populated, the output will be: "His dog barks at night" (no additional conversion will happen either)

        But for the task here the code could look like in my suggestion:

        print('{0:>{w}d} {0:>{w}o} {0:>{w}X} {0:>{w}b}'.format(i, w=len(bin(n))-2))
        

        I will keep it brief, but since I am reusing the variable "i", which is within the scope of format() and I don't want to type it in like '{}{}{}{}'.format(i, i, i, i), I just specified to use the 0 position argument every time, so I won't have to multiply code needlessly.

        I am also using a variable to specify the width and align of each printed out "i" and then to also apply data type conversions on the fly. In {0:>{w}b} it means, that I want the 0 pos argument to be used (0), I want the ouput to be aligned to the right (>), I want it to have the specified width ({w} as width variable, this can also be set statically as a digit i.e. "2") and I want the data to be converted to binary on the fly.

        Take a look in the docs here for a really good explanation: https://www.programiz.com/python-programming/methods/string/format

        I hope that helps.

        • + 0 comments

          amazing!!! thanks a lot for the explanation. very helpful

    • + 1 comment

      I agree that it's all about formatting. I like the example provided here because it's very concise like what I went with, although I would still shorten it a bit:

      def print_formatted(n):
      	for i in range(1, n+1):
      		print('{0:>{w}d} {0:>{w}o} {0:>{w}X} {0:>{w}b}'.format(i, w=len(bin(n))-2))
      

      I ended up circling back to my first solution after trying several other approaches and then finally noticing an astray digit just before the binary conversion...

      • + 0 comments

        Can you please explain this line? Why -2 is used?

        format(i, w=len(bin(n))-2)

    • + 1 comment

      what are you doing by writing width=width

      • + 0 comments

        The first 'width' is a keyword, the second is the variable.

    • + 3 comments

      This is seriously messed up as I truly believe something is missing in the problem statement:

      This doesn't work for testcase 2 even though it produces exactly the same and can be validated separately

      def print_formatted(number):

      w = len(str(bin(number)).replace('0b',''))
      
      for num in range(1, number+1):
      
          dec = str(num)
          oc_ = str(oct(num)).replace('0o','')
          he_ = str(hex(num)).replace('0x','')
          bi_ = str(bin(num)).replace('0b','')
      
          print(dec.rjust(w), oc_.rjust(w), he_.rjust(w), bi_.rjust(w), sep=' ')
      
      • + 1 comment

        The hexadecimal portion must be in uppercase if it contains letter(s). So try:

        he_ = str(hex(num)).replace('0x','').upper()

        • + 0 comments

          was going crazy trying to figure out why the test cases weren't passing. this got it

      • + 0 comments

        Try this: he_ = str(hex(num)).replace('0x','').upper()

      • + 1 comment

        why did you use sep=' '

        • + 0 comments

          The separator between the arguments to print() function in Python is space by default. The ‘sep’ parameter is used to achieve the same, it is found only in python 3.x or later. It is also used for formatting the output strings. for ex

          code for disabling the softspace feature

          print('G','F','G', sep='')

          for formatting a date

          print('09','12','2016', sep='-')

          another example

          print('pratik','geeksforgeeks', sep='@')

    • + 1 comment

      I can't understand the second statement...

      width = len("{0:b}".format(n))

      what is "{O:b} ? What does it mean?

      • + 0 comments

        str.format() allows for positional replacement fields. See https://docs.python.org/3/library/stdtypes.html#str.format and https://docs.python.org/3/library/string.html#formatstrings

        In this case, the 0 is the placeholder for n, and :b means to use Binary format.

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

        I am new to python Any one please explain l1 = len(bin(number)[2:]) this line?

        • + 0 comments

          bin(number) converts number from an int to a binary number. The binary number includes the prefix "0b". He is slicing the string and grabbing everything after 0b (something like '10111'). By doing len(), he is getting the length of the binary number, which is how you determine the space padding between the numbers.

    • + 0 comments

      for more explanation go to this link https://www.programiz.com/python-programming/methods/string/format

      you'll get it

    • + 0 comments

      We can learn formatting in python in this site

    • + 1 comment

      Thank you for your code

      • + 0 comments

        You are welcome :)

    • + 0 comments

      {0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}, could you please explain this line, as to how it is printing the numbers correctly. I tried to print the same and had got ox1, ox2 for printing octal numbers and similarly for hexadecimal values.

      I am new to python and want to know how this works.

    • + 2 comments

      Python 3 implementstion:

      def print_formatted(number):
          number += 1
          for i in range(1, number):
          octal, hexal, binar = "","",""
          width = len(str(bin(number - 1))) - 1
          for j in str(bin(i))[::-1]:
              if j == "b":
                  break
              else:
                  binar = j + binar
          for j in str(oct(i))[::-1]:
              if j == "o":
                  break
              else:
                  octal = j + octal
          for j in str(hex(i))[::-1]:
              if j == "x":
                  break
              else:
                  hexal = j + hexal
          print(str(i).rjust(width - 1)+octal.upper().rjust(width)+hexal.upper().rjust(width)+binar.rjust(width))
      
      • + 0 comments

        is this code gives desired output?

    • + 0 comments

      not able to understand it.

    • + 0 comments

      can anyone explain me the above logic as well as syntax i am not clear with that

    • + 0 comments

      width = len("{0:b}".format(n)) can someone tell me what does this statement is doing

    • + 0 comments

      can you explain why we are using ,width=width width value is already obtained ryt?

    • + 0 comments

      nice

    • + 0 comments

      Can u please explain how this solution works? I got error while experimenting:

      1) print("{0:{5}b}".format(i))

      2) w=5 print("{0:{w}b".format(i, w))

      it tells i need to give format as .format(i,width =w)

      while .format(i,w) while defining w=5 earlier Fails, which doesnt make sense.

      Please explain!!

    • + 1 comment

      print "{0:{width}d}

      Why zero after'{' this bracket {0:

                                                          plz ans me
      
      • + 0 comments

        When we print a binary or any number like:

        print("{}".format(bin(12)))

        The o/p we get is:

        0b1100

        So the given format is to exclude 0b. In your example: 0d for decimal.

    • + 0 comments

      why are we setting width to len("{0:b}".format(n) ???

    • + 0 comments

      what is mean of {0:b} ?

    • + 0 comments

      what does b in this stmt [width = len("{0:b}".format(n))] refer to ? and why we need to get width?

    • + 0 comments

      Maybe the question has been changed, this will not get the upper case of hex.

    • + 0 comments

      please explain this code

    • + 0 comments

      No need of width =width if you want to do like this

      "n =number

      width = len("{0:b}".format(n))

      for i in xrange(1,n+1):

      print "{0:{1}d} {0:{1}o} {0:{1}X} {0:{1}b}".format(i, width)"

                  As he not used 1 he used width =width
                  to understand clearly put 1 instead of width and remove width = width and place width in format
      
    • + 0 comments

      def print_formatted(number):
      w = len("{0:b}".format(number))
      for i in range(1,number+1): b=bin(i)[2:] o=oct(i)[2:] h=str(hex(i)[2:]).upper() print('{:>{w}} {:>{w}} {:>{w}} {:>{w}}'.format(i,o,h,b,w=w))

    • + 0 comments

      This does not work in python 3

    • + 0 comments

      can anyone explain this line ------> width = len("{0:b}".format(n)) why used len(bin_value) plz explain

    • + 1 comment

      Updated version of this solution in Python 3 using f-strings:

      def print_formatted(number):
          space = len(f"{number+0:b}")
          for i in range(1,number+1):
              print(f"{i+0:{space}d} {i+0:{space}o} {i+0:{space}X} {i+0:{space}b}")
      
      if __name__ == '__main__':
          n = int(input())
          print_formatted(n)
      
      • + 0 comments

        thank you! that what I was looking for. didn't know u can have nested "{}"! However, the 0 is redundent. this worked for me as well in python3

        l = len(f"{number:b}")
        
        for i in range(1,number+1):
            print(f"{i:{l}} {i:{l}o} {i:{l}X} {i:{l}b}", )
        
    • + 0 comments

      how did you derive this width = len("{0:b}".format(n))?

    • + 0 comments

      really nice approach

    • + 0 comments

      def print_formatted(n): width = len("{0:b}".format(n)) for i in range(1,n+1): print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width))

                  ---Python 3
      
    • + 0 comments

      Tricky one bro... Thanks for the help...

    • + 0 comments

      It works. Thanks for sharing.

    • + 0 comments

      will you please explain whats the purpose of putting zero before : in format specifier

    • + 0 comments

      Great solution!

    • + 0 comments

      Can you please explain your code?

    • + 0 comments

      what is the use of width? I am a beginner and i dont understand why it is used

    • + 1 comment

      This code gives an error, "TypeError: unsupported operand type(s) for -: 'str' and 'int'"

      Someone please tell me what it is and how to fix it.

      number = int(input())
      
      for i in range(1, number+1):
          print(str(i).rjust(len(bin(i) - 2)))
          print(oct(i)[2:].rjust(len(bin(i) - 2)))
          print(oct(i)[2:].rjust(len(bin(i) - 2)))
          print(oct(i)[2:].rjust(len(bin(i) - 2)))
      
      • + 0 comments

        len(bin (i) ) = Use Bracket properly

    • + 0 comments

      can you plzz explain how print statement works???

    • + 0 comments

      0:{width}d can you explain this

    • + 0 comments

      could u please explain me the usage of "b" in{0:b}"

    • + 0 comments

      for i in range(1,number+1): print(i,oct(i).replace("0o", ""),hex(i).replace("0x", ""),bin(i).replace("0b", ""))

    • + 0 comments

      Can you explain this

    • + 0 comments

      Taking inspiration from trinhhoangnhu, here's a Python 3.6+ version using Literal String Interpolation.

      def print_formatted(number):
          width = len(bin(number)[2:]) #cut off start of bin(number) - 0b
          for i in range(1,number+1):
              print(f"{i:{width}d} {i:{width}o} {i:{width}X} {i:{width}b}")
      
    • + 0 comments

      could uh please explain this codse...i didn't understand the second line of ths code.....

    • + 0 comments

      can someone explain this program!!!

    • + 0 comments

      Someone please explain this part of the print statement, "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}"

    • + 0 comments

      can any one explain this code??

    • + 0 comments

      please tell what is width = width doing and why we are finding the width of the input in binary form

    • + 0 comments

      You can also get width this way:

      width = n.bit_length()

    • + 0 comments

      why are we converting the length to binary?

    • + 0 comments

      user = int(input())

      for i in range(1,user+1): print(i, end=" ") a = str(oct(i)) print(a[2:],end=" ") b = str(hex(i)) print(b[2:],end=" ") c = str(bin(i)) print(c[2:])

    • + 0 comments

      Yes it's working for python2 but when i convert it into python3 I can't get correct formatted output. Why is that? What is causing that problem?

    • + 0 comments

      you can also do it like this...

      print("{0:{1}d} {0:{1}o} {0:{1}X} {0:{1}b}".format(i,width))

    • + 0 comments

      Good way to get the length of binary format.

    • + 0 comments

      You could use list comprehension to get rid of the for loop:

      width = len("{0:b}".format(number))
      [print(("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}").format(x, width=width)) for x in range(1, number+1)]
      
    • + 0 comments

      Can someone explain why the {0:{width}b} in the print func when the width = 2 and the output is 2 2 2 10

      is only adding a padding of 1 after the 3rd column and not 2 ?

    • + 0 comments

      This tutorial section is very educational. Pharmaceutical grade CBD oil Thanks for holding it. This problem on String Formatting is very much informative and helps the students to learn maths in a very interesting way. All the doubts can be discussed here and hence can be solved.

    • + 0 comments

      Same solution using python3's latest f-strings

      def print_formatted(n):
          width = (len(("{0:0b}".format(n))))
          for i in range(1,n+1):
              print(f"{i:>{width}} {i:>{width}o} {i:>{width}X} {i:>{width}b}")
      				
      
    • + 0 comments

      I have been interested in how we can use a variable as a number of spaces for a long time and found it here. Thanks a lot <3

    • + 0 comments

      Can somebody explain this solution?

    • + 0 comments

      l=len(bin(number)[2:]) for i in range(1,number+1): dec=str(i) octal=oct(i)[2:] hexadec=hex(i)[2:] binary=bin(i)[2:] print(dec.rjust(l,' '),octal.rjust(l,' '),(hexadec.upper()).rjust(l,' '),binary.rjust(l,' '))

    • + 1 comment

      DRY Python 3 version:

      def print_formatted(number):
          width = len('{:b}'.format(number))
          for num in range(1, n+1):
              print(*('{i:{w}{b}}'.format(i=num, w=width, b=base) for base in 'doXb'), sep=' ', end='\n')
      
      • + 0 comments

        Or a slightly more readable version:

        def print_formatted(number):
            width = len('{:b}'.format(number))
            for num in range(1, n+1):
                for base in 'doXb':
                    print(('{i:{w}{b}}'.format(i=num, w=width, b=base)), end=' ')
                print()
        
    • + 0 comments

      Could you explain the width implementation in string format? I've understood the format method in string

    • + 0 comments

      Can anyone explain why the width value is not the same as n? In other words, when n = 5, width is equal to 3, when n = 10, width is equal to 4.

    • + 0 comments

      python3 can 1 line

      [print('{0:={vs}} {0:={vs}o} {0:={vs}X} {0:={vs}b}'.format(i,vs=len("{0:b}".format(number)))) for i in range(1,number+1)]
      
    • + 0 comments

      Can someone please explain why hackerrank rejected my solution for every test case except test case 0? here is the code:

      def setw(n):
          s = ''
          for i in range(n):
              s += ' '
          return s
      
      def print_formatted(number):
          # your code goes here
          b = len(str(bin(number)[2:]))
          for i in range(1, number+1):
              print(setw(b-len(str(i))), i,' ', setw(b-len(str(oct(i)[2:]))), oct(i)[2:], ' ', setw(b-len(str(hex(i)[2:]))), hex(i)[2:], ' ', setw(b-len(str(bin(i)[2:]))), bin(i)[2:], sep='')
      
      if __name__ == '__main__':
          n = int(input())
          print_formatted(n)
      

      The code outputs the exact same digits at the exact same position but hackerrank is not accepting it.