Python format() 打印十进制、八进制、十六进制和二进制值

Pun*_*nha 0 python format binary hex

我正在尝试.format()在想要打印的 python 中使用

1 到 N 以空格填充,以便所有字段都采用与二进制值相同的宽度。

以下是我迄今为止尝试过的

n=int(input()) 
width = len("{0:b}".format(n)) 
for num in range(1,n+1):
    print ('  '.join(map(str,(num,oct(num).replace('0o',''),hex(num).replace('0x',''),bin(num).replace('0b','')))))
Run Code Online (Sandbox Code Playgroud)

我不知道如何在.format()这里正确使用该功能。请帮忙

Sau*_*abh 9

下面的代码查找所有十六进制、二进制、八进制和十进制值

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))
Run Code Online (Sandbox Code Playgroud)


小智 5

# the simplest one.

def print_formatted(number):
    width=len(bin(number)[2:])
    for i in range(1,number+1):
        deci=str(i)
        octa=oct(i)[2:]
        hexa=(hex(i)[2:]).upper()
        bina=bin(i)[2:]
        print(deci.rjust(width),octa.rjust(width),hexa.rjust(width),bina.rjust(width))
Run Code Online (Sandbox Code Playgroud)