We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
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:])
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.
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.
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.
-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
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
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
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.
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.
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.
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)))
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, ' '))
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)))])
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:]))))
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 :)
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.
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.
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')
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
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"))
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
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):
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).
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 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)
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( ).
"{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/
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
"{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/
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('{}dogbarksat{}!'.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:
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.
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:
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...
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
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:{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.
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))
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))
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)]
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.
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,' '))
String Formatting
You are viewing a single comment's thread. Return to all comments →
This is all about formatting so...
here is python problem solution https://programs.programmingoneonone.com/2021/01/hackerrank-string-formatting-solution-python.html
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.
because bin(N) also contain 0b as prefix
eliminates the spaces in your output
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.
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:])
To reduce space between outputs as show in test case output
could you get the answer?....len(bin(N))-2? if yes then please explain me!!!
Yep! it worked for me and please refer to yaswanthpalika(my above comment thread) for detailed answer, thank you
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')
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.
because it has 0b before any binary number, so you need to take those two from the length
bin(10) returns
0b10
whereas what you want is10
. The0b
is the representation that the number is a binary and is the same for0x
(for hex) and0o
(for octal). So when formating it we need to-2
from the length to properly format the string.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.
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
-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
you can simply use len(format(n,'b')) if u dont want to use -2
very True
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
what is d,o,X,b ?? i couldnt understand that part. Can you please tell me in detail?
It looks like it forces the number to d(ecimal), o(ctal), (he)X and b(inary).
decimal octal hexadecimal and binary
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'
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 :)
D stands for decimal, O stands for octal, X stands for Hexadecimal, b for binary, hope you understood
decimal, oct, hex, binary
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
Updated solution is here
https://www.thecscience.com/2021/06/HackerRank-string-formatting-in-python-problem-solution.html
pls dont post soultion people dont learn then idiot
stop putting soultion u moron
frick u
Can someone please explain why hackerrank rejected my solution for every test case except test case 0? here is the code:
The code outputs the exact same digits at the exact same position but hackerrank is not accepting it.
can u pls explain y we have taken len("{0:b}".format(n)) overthere? pls explain total program if possible
can u please tell me what is xrange?
backwards i think so if your doing from 1 to 10, with xrange it will be from 10 to 1
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.
xrange atually means to do it double the times you make it do
thats my brother trying to trick you, he lies
cap
stop, i'm trying to help someone!
stop the cap hes lying and hes not my brother i reproted him
stop
you both are wrong. xrange prints given number of xmas trees in the output. dumbasses
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.
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.
Easy Sol. -- https://codecracksol.blogspot.com/2022/03/string-formatting.html
can you please explain this format() function?? --a beginner
please do refer this https://pyformat.info/
Thank you..
awesome resorce thank you for sharing!
Great fresource for beginners!
Realy It's help full
Nice reference bro
thanks
Thank u for sharing ...was very helpful.
can we know if there any similar sites for other topics too in python thanks in advance bro
https://data-flair.training/blogs/python-tutorials-home/
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):
This is a method that we are more familiar
bin(i)[2:] is a string already, no need to converte again.
yeah.. thats right
are hex,oct and bin always strings?
Yes
Could you explain the line
This line of code responses to this requirement: "Each value should be space-padded to match the width of the binary value of n."
but why widhth for every value is len of binary value?
because the challenge want us to do so
this is string slicing. bin function return string. str="abcd" then output of str[2:] is cd.
taking the value from 2 digit so it can ignore 0x
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.
See the python documentation for the bin() function.
"converts an integer number to a binary string prefixed with 0b"
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.
the 2: removes the 0o stuff person from 5 years ago
should be
Otherwise, we have an "o" before the octal answer.
can u pls tell me how rjust(w,' ') works??
You can refer to the previous challenge. Basically it means adjusting to the right with width w and empty space filled with whitespace ie. ('').
is it necessary to specify the whitespace padding?? isn't it the defaut valu???
It isn't necessary. Default is white space
i am your yur big fan #Golmal series when did you start coading huh ?
6 years ago
hahahaaaa.....
hahaha
"o" is in Python 3, in Python 2 there is only a zero
actually its 0o,so using[2:] will do
plz explane this line : w=len(bin(st)[2:]) why u use [2:] and also use of sep=' '
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.
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:
I am not sure if we can import modules.
if it is not passing, that means
not working here
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, ' '))
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)))])
same problem here
replace str(oct(i))[1:] with replace str(oct(i))[2:]
Remove the first space " " in print and use rjust(len(str(bin(number)[2:]))) The below code works perfectly def print_formatted(number):
why are we using width as len(str(bin(n)) in every case??
surely bin(5) returns 0b101
how this rjust() works
why upper() is used?
because the question asks to print capital hexadecimal equivalents
I used same method and on the pycharm I get same output, however I could not submit hear :(
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.
rjust(w,' ') space not needed herer as it is taken by default
Sorry I am a beginner, may I know what [1:] does in the str function str(oct(i)[1:]) ?
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 :)
Thanks a lot :)
It could be just : w = st.byte_length()
Found this comment. Suprised no one was giving an up. Smart use of count, though I have to use bit_length() instead.
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
correction: str(oct(i)[2:]) instead of str(oct(i)[1:])
Thanks a lot. I was doing the rjust thing wrong before going through your solution.
It worked without the sep = ' '
why have you used //str(hex(i)[2:].upper()).rjust(w,' ')// I'mma noob
why does it fail some of the test cases?
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
don't use sep=' ' as we are already ussing space as a filler.
str(hex(i)[2:].upper()) why we are converting into upper
please make a correct ..it will be str(oct(i)[2:]).rjust(w,' ') thanks for the code
Easy to understand for a begineer . Thank You !
why we can't use "+" sign instead of " , "
why did you took the substring from 2 ?
use str(oct(i)[2:]).rjust(w,' ') instead of str(oct(i)[1:]).rjust(w,' ').Thanks for ur code...
This code is not giving the required output .
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.
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.
in w=len(bin(st)[2:]) why did u took [2:] in the statement?
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.
Thank you
No need to use pass the parameter sep=" ", given that it is already set by default as ' '.
why rjust(w,' ')?
This is what I got
It should be str(oct(i)[2:]), since the oct() function always returns '0o' before the base-8 number
good one
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
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))
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
that's straight up witchcraft what you did there
This is a new way of formatting. So many new things to learn :-o
To get the number of bits of n, why isn't
len("{0:{0}b}".format(n))
working?The
{0}
part does a right justification withn
insideformat
. Hopefully this explains what I mean a bit more (did this in a Python 3.5 interpreter on Windows 10):for more reference https://www.geeksforgeeks.org/python-format-function/
What is the importance of width=width?
Without
width=width
, the code would not run (asformat
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 thewidth
variable defined at line 2.If you're asking why
{width}
is there, then it tellsformat
to space out the output of each number to the largest number string (which is found out by line 2 of the code).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?
Put in another way, how does format have no idea what width should be set to? Isn't width set in line 2 already?
It's because they're two different variables.
width
in line 2 belongs to the user program, while the otherwidth
belongs to theformat
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:
Which returns the following:
def func(x): return x + x
x = 12 print(func(x))
will you please explain.
can you please explane the use of width and with=width
don't think the line width = width
change the code to
thanks that worked for me in python 2
Not working for Python 3
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)
Can you please explain?
can you explain wht is w?? i mean how it works??
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( ).
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))
Can you please explain this line. Thanks
"{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/
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
why this
"{0:b}"
"{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/
Please elaborate this width function in detail
Well done, I couldnt get the proper framing of this, this is VERY VERY clear and well done
Thank you it works..but can u elaborate what you have done or the concept???
I tried this method but its showing "Unknown format code 'w' for object of type 'int'"
Can you explain your code
width = len("{0:b}".format(n)) what does this line do? -a Beginner
{0:{width}d} what does 0 here denote?
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:
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:
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.
amazing!!! thanks a lot for the explanation. very helpful
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:
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...
Can you please explain this line? Why -2 is used?
format(i, w=len(bin(n))-2)
what are you doing by writing width=width
The first 'width' is a keyword, the second is the variable.
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):
The hexadecimal portion must be in uppercase if it contains letter(s). So try:
was going crazy trying to figure out why the test cases weren't passing. this got it
Try this: he_ = str(hex(num)).replace('0x','').upper()
why did you use sep=' '
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='@')
I can't understand the second statement...
width = len("{0:b}".format(n))
what is "{O:b} ? What does it mean?
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.
I am new to python Any one please explain l1 = len(bin(number)[2:]) this line?
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.
for more explanation go to this link https://www.programiz.com/python-programming/methods/string/format
you'll get it
We can learn formatting in python in this site
Thank you for your code
You are welcome :)
{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.
Python 3 implementstion:
is this code gives desired output?
not able to understand it.
can anyone explain me the above logic as well as syntax i am not clear with that
width = len("{0:b}".format(n)) can someone tell me what does this statement is doing
can you explain why we are using ,width=width width value is already obtained ryt?
nice
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!!
print "{0:{width}d}
Why zero after'{' this bracket {0:
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.
why are we setting width to len("{0:b}".format(n) ???
what is mean of {0:b} ?
what does b in this stmt [width = len("{0:b}".format(n))] refer to ? and why we need to get width?
Maybe the question has been changed, this will not get the upper case of hex.
please explain this code
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)"
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))
This does not work in python 3
can anyone explain this line ------> width = len("{0:b}".format(n)) why used len(bin_value) plz explain
Updated version of this solution in Python 3 using f-strings:
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
how did you derive this width = len("{0:b}".format(n))?
really nice approach
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))
Tricky one bro... Thanks for the help...
It works. Thanks for sharing.
will you please explain whats the purpose of putting zero before : in format specifier
Great solution!
Can you please explain your code?
what is the use of width? I am a beginner and i dont understand why it is used
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.
len(bin (i) ) = Use Bracket properly
can you plzz explain how print statement works???
0:{width}d can you explain this
could u please explain me the usage of "b" in{0:b}"
for i in range(1,number+1): print(i,oct(i).replace("0o", ""),hex(i).replace("0x", ""),bin(i).replace("0b", ""))
Can you explain this
Taking inspiration from trinhhoangnhu, here's a Python 3.6+ version using Literal String Interpolation.
could uh please explain this codse...i didn't understand the second line of ths code.....
can someone explain this program!!!
Someone please explain this part of the print statement, "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}"
can any one explain this code??
please tell what is width = width doing and why we are finding the width of the input in binary form
You can also get width this way:
why are we converting the length to binary?
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:])
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?
you can also do it like this...
Good way to get the length of binary format.
You could use list comprehension to get rid of the for loop:
Can someone explain why the
{0:{width}b}
in the print func when the width = 2 and the output is 2 2 2 10is only adding a padding of 1 after the 3rd column and not 2 ?
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.
Same solution using python3's latest f-strings
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
Can somebody explain this solution?
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,' '))
DRY Python 3 version:
Or a slightly more readable version:
Could you explain the width implementation in string format? I've understood the format method in string
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.
python3 can 1 line
Can someone please explain why hackerrank rejected my solution for every test case except test case 0? here is the code:
The code outputs the exact same digits at the exact same position but hackerrank is not accepting it.