使用 f-strings 格式化字符串宽度
Formatting string width with f-strings
我正在尝试创建给定宽度的 headers 并想使用
>>> print(f'{"string":15<}|')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: Unknown format code '<' for object of type 'str'
我们是想像这样拼凑 headers 还是我遗漏了一些有关 f 字符串的信息?
print('string'+" "*(15-len('string'))+"|")
string |
我想你要找的只是print(f'{"string":15}|')
根据 Python Format Specification Mini-Language,对齐说明符(例如 <
)必须位于宽度说明符(例如 15
)之前。考虑到这个标准,格式字符串的正确表述是 {:<15}
。但是,left-alignment 是默认推断的字符串,因此您可以将其简单地写为 {:15}
.
>>> print(f'{"string":<15}|')
string |
>>> print(f'{"string":15}|')
string |
我正在尝试创建给定宽度的 headers 并想使用
>>> print(f'{"string":15<}|')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: Unknown format code '<' for object of type 'str'
我们是想像这样拼凑 headers 还是我遗漏了一些有关 f 字符串的信息?
print('string'+" "*(15-len('string'))+"|")
string |
我想你要找的只是print(f'{"string":15}|')
根据 Python Format Specification Mini-Language,对齐说明符(例如 <
)必须位于宽度说明符(例如 15
)之前。考虑到这个标准,格式字符串的正确表述是 {:<15}
。但是,left-alignment 是默认推断的字符串,因此您可以将其简单地写为 {:15}
.
>>> print(f'{"string":<15}|')
string |
>>> print(f'{"string":15}|')
string |