如何在Python中正确格式化输出?

时间:2019-10-25 16:48:00

标签: python-3.x binary type-conversion hex octal

这是我的代码:

def print_formatted(number):
    for i in range(1,number+1):
        print("{0: d} {0: o} {0: x} {0: b}".format(i)) 

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

预期的输出和我的输出在下面给出的图像链接中。

This is the image of my output and the expected output in hackerrank

This is the code i have written.

2 个答案:

答案 0 :(得分:0)

假设这是HackerRank的“字符串格式” Python挑战,那么您的代码缺少的是“每个值都应进行空格填充以匹配n的二进制值的宽度”。部分说明。因此,您需要确定函数的“数字”输入参数的二进制版本的位数(以位数为单位),然后打印数字从1到“数字”的十进制,八进制,十六进制和二进制版本中的每一个,并使用前导空格,再次匹配该长度。在屏幕快照的示例测试用例中,由于二进制中的2(即10)是两位数长,所以您打印的所有只有一位数长的数字都需要用前导空格填充,例如“ 1”而不是“ 1”。

答案 1 :(得分:0)

for i in range(number):
    i = i+1
    
    pad = len("{0:b}".format(number))
    width = ''
    for j in range(pad):
        width = width + ' '
    # print ("{}".format(width) + "{0:o}".format(int(i)), end="")
    # print ("{}".format(width) + "{0:X}".format(int(i)), end="")
    # print ("{}".format(width) + "{0:b}".format(int(i)))
    print ("{}".format(i).rjust(pad, ' '), end="")
    print (("{0:o}".format(int(i))).rjust(pad+1, ' '), end="")
    print (("{0:X}".format(int(i))).rjust(pad+1, ' '), end="")
    print (("{0:b}".format(int(i))).rjust(pad+1, ' '))