String数字的格式


def print_formatted(n):
for i in range(1,n+1):
print(str(i)+' '+str(oct(i)[2:])+' '+str(hex(i)[2:])+' '+str(bin(i)[2:]))

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

问题是使用循环从给定的数字打印八进制十六进制和更多类型的数字。我得到了相同的数字,但我不知道如何制作"空格"。要求二进制数(可在最后一列PIC中看到)

https://i.stack.imgur.com/LVRhm.png

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

试试上面这个

尝试如下:

from typing import List
def get_largest_number_size(lines: List[List[str]]) -> int:
"""Returns the size of the largest element/number in the lines to be printed"""
nlargest = 0
for line in lines:
for element in line:
nlargest = max(nlargest, len(element))
return nlargest
def print_formatted(n: int) -> None:
lines = []
for i in range(1,n+1):
line = [str(i), str(oct(i)[2:]), str(hex(i)[2:]), str(bin(i)[2:])]
lines.append(line)
nlargest = get_largest_number_size(lines)
for line in lines:
for i, element in enumerate(line):
# align the numbers
line[i] = element.rjust(nlargest)
print(" ".join(line))

使用例子:

print_formatted(5)

输出:

1   1   1   1
2   2   2  10
3   3   3  11
4   4   4 100
5   5   5 101

相关内容

  • 没有找到相关文章

最新更新