Python3 .format() 对齐用法

Python3 .format() align usage

谁能帮我改一下这几行的写法? 我想让我的代码使用 .format() 更优雅,但我真的不知道如何使用它。

print("%3s %-20s %12s" %("Id", "State", "Population"))
print("%3d %-20s %12d" %
            (state["id"],
             state["name"],
             state["population"]))

您的格式很容易转换为 str.format() formatting syntax:

print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
print("{id:3d} {name:20s} {population:12d}".format(**state))

请注意,left-alignment 是通过在宽度前加上 < 而不是 - 来实现的,并且字符串的默认对齐方式是 left-align,因此 [=16] =] 需要 header 字符串并且 < 可以省略,但格式密切相关。

这通过使用格式本身中的键直接从 state 字典中提取值。

你也可以直接使用第一种格式的实际输出结果:

print(" Id State                  Population")

演示:

>>> state = {'id': 15, 'name': 'New York', 'population': 19750000}
>>> print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
 Id State                  Population
>>> print("{id:3d} {name:20s} {population:12d}".format(**state))
 15 New York                 19750000

你可以这样写:

print("{id:>3s} {state:20s} {population:>12s}".format(id='Id', state='State', population='Population'))
print("{id:>3d} {state:20s} {population:>12d}".format(id=state['id'], state=state['name'], population=state['population']))

请注意,您必须使用 > 来右对齐,因为默认情况下项目是左对齐的。您还可以在格式化字符串中命名项目,这样可以更清楚地了解值的位置。