如何使用变量而不是花括号内的数字来格式化字符串?

How to format a string using variables instead of numbers within curly braces?

我使用的是 Python 3.7,我在变量中存储了一个值。该变量保存我想在花括号内用于字符串格式化的填充值。代码解释了我要做什么。

def print_formatted(number):
    for i in range(1, number + 1):
        binum = bin(i).replace('0b', '')
        ocnum = oct(i).replace('0o', '')
        hexnum = hex(i).replace('0x', '')

        length = len(bin(number).replace('0b', ''))
        print('{0:>length} {1:>length} {2:>length} {3:>length}'.format(i, ocnum, hexnum, binum)) # Error here

这是我一直在尝试的代码 运行。我想要做的是通过用最后一个二进制数的长度值填充它来右对齐数字。

ValueError: Invalid format specifier

这是我得到的错误。我做错了什么?

您必须首先将变量 length 的值合并到您的格式字符串中,奇怪的是,使用 .format() 是最好的方法。

更改以下行

print('{0:>length} {1:>length} {2:>length} {3:>length}'.format(i, ocnum, hexnum, binum))

print('{{0:>{length}}} {{1:>{length}}} {{2:>{length}}} {{3:>{length}}}'.format(length=length).format(i, ocnum, hexnum, binum))

我通常分两步进行,首先创建格式字符串。它通过转义大括号 - {{,}} - 需要保留在格式字符串中来工作。

>>> length = 4
>>> f'{{:>{length}}} {{:>{length}}} {{:>{length}}} {{:>{length}}}'
'{:>4} {:>4} {:>4} {:>4}'
>>> 


fmt = f'{{:>{length}}} {{:>{length}}} {{:>{length}}} {{:>{length}}}'
print(fmt.format(i, ocnum, hexnum, binum))

您可以使用 f-strings.

def print_formatted(number):
    length = len(bin(number)) - 2
    for i in range(1, number + 1):
        ocnum = oct(i)[2:]
        hexnum = hex(i)[2:]
        binum = bin(i)[2:]
        print(' '.join(f'{n:>{length}}' for n in (i, ocnum, hexnum, binum)))

>>> print_formatted(20)
    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
   10    12     a  1010
   11    13     b  1011
   12    14     c  1100
   13    15     d  1101
   14    16     e  1110
   15    17     f  1111
   16    20    10 10000
   17    21    11 10001
   18    22    12 10010
   19    23    13 10011
   20    24    14 10100

您可以使用 f 字符串和格式说明符来避免使用 hexoctbin 内置函数,然后使用字符串切片并改用 int.bit_length()取二进制字符串的长度,例如:

def print_formatted(number):
    # get number of bits required to store number
    w = number.bit_length()
    for n in range(1, number + 1):
        # print each number as decimal, then octal, then hex, then binary with padding
        print(f'{n:>{w}} {n:>{w}o} {n:>{w}x} {n:>{w}b}')

运行 print_formatted(20) 会给你:

    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
   10    12     a  1010
   11    13     b  1011
   12    14     c  1100
   13    15     d  1101
   14    16     e  1110
   15    17     f  1111
   16    20    10 10000
   17    21    11 10001
   18    22    12 10010
   19    23    13 10011
   20    24    14 10100