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.
The below in-built functions can be used to convert the incoming number value to it's respective representations:
1. Integer to Octal: oct()
2. Integer to Hexadecimal: hex()
3. Integer to Binary: bin()
The above functions will return the octal, hexadecimal and binary representations of the number. However, the representations returned will have the notations, "0o", "0x" and "0b". We do not need these notations in the final output. Therefore, we slice the returned values from 2nd position onwards (2[:]).
Now, coming to the next part where each value should be space-padded to match the value of the width of the binary value of the number and the values should be separated by a single space.
For this we can calculate the required padding by taking the length of the binary representation of the number and subtracting 2 from it (len(bin(number)) - 2). The logic behind this can be found from the sample output that is being shown in the given problem.
After we get the padding value, we right justify (rjust) the result values with this padding value and print the final output.
Note: The decimal representation has to be converted to string first as rjust cannot be used with integer values.
String Formatting
You are viewing a single comment's thread. Return to all comments →
The below in-built functions can be used to convert the incoming number value to it's respective representations: 1. Integer to Octal: oct() 2. Integer to Hexadecimal: hex() 3. Integer to Binary: bin()
The above functions will return the octal, hexadecimal and binary representations of the number. However, the representations returned will have the notations, "0o", "0x" and "0b". We do not need these notations in the final output. Therefore, we slice the returned values from 2nd position onwards (2[:]).
Now, coming to the next part where each value should be space-padded to match the value of the width of the binary value of the number and the values should be separated by a single space.
For this we can calculate the required padding by taking the length of the binary representation of the number and subtracting 2 from it (len(bin(number)) - 2). The logic behind this can be found from the sample output that is being shown in the given problem.
After we get the padding value, we right justify (rjust) the result values with this padding value and print the final output.
Note: The decimal representation has to be converted to string first as rjust cannot be used with integer values.