使用 f 字符串格式化字符串宽度

Ray*_*emi 2 python f-string

我正在尝试创建给定宽度的标题并想使用

>>> print(f'{"string":15<}|')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: Unknown format code '<' for object of type 'str'
Run Code Online (Sandbox Code Playgroud)

我们是否打算像这样拼凑标题,还是我遗漏了有关 f 字符串的内容?

print('string'+" "*(15-len('string'))+"|")
string         |
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 8

根据 Python格式规范迷你语言,对齐说明符(例如<)必须位于宽度说明符(例如15)之前。考虑到这个标准,格式字符串的正确公式是{:<15}. 但是,默认情况下会推断字符串左对齐,因此您可以将其简单地写为{:15}.

>>> print(f'{"string":<15}|')
string         |
>>> print(f'{"string":15}|')
string         |
Run Code Online (Sandbox Code Playgroud)