python 3 中的可变字符串格式

Variable string formatting in python 3

输入一个数字,例如9 我想打印从 1 到 9 的十进制、八进制、十六进制和二进制值,如:

1     1     1     1
2     2     2    10
3     3     3    11
4     4     4   100
5     5     5   101
6     6     6   110
7     7     7   111
8    10     8  1000
9    11     9  1001

如何在 python3 中使用

之类的语法实现此目的
dm, oc, hx, bn = len(str(9)), len(bin(9)[2:]), ...
print("{:dm%d} {:oc%s}" % (i, oct(i[2:])) 

我的意思是,如果数字是 999,那么我希望将十进制 10 打印为“10”,而 999 的二进制等价物是 1111100111,因此我希望将 10 打印为“1010”。

您可以使用 str.format() and its mini-language 为您完成所有事情:

for i in range(1, 10):
    print("{v} {v:>6o} {v:>6x} {v:>6b}".format(v=i))

将打印:

1      1      1      1
2      2      2     10
3      3      3     11
4      4      4    100
5      5      5    101
6      6      6    110
7      7      7    111
8     10      8   1000
9     11      9   1001

更新:要在变量中定义字段'widths',您可以使用格式内格式结构:

w = 5  # field width, i.e. offset to the right for all octal/hex/binary values

for i in range(1, 10):
    print("{v} {v:>{w}o} {v:>{w}x} {v:>{w}b}".format(v=i, w=w))

或者为每个字段定义不同的宽度变量 type 如果您希望它们的间距不均匀。

顺便说一句。因为你已经用 python-3.x, if you're using Python 3.6 or newer, you can use Literal String Interpolation 标记了你的问题以进一步简化它:

w = 5  # field width, i.e. offset to the right for all octal/hex/binary values

for v in range(1, 10):
    print(f"{v} {v:>{w}o} {v:>{w}x} {v:>{w}b}")