0

我从 Python 文档中读取了格式字符串迷你语言并尝试这样做:

a = 20000 # I want "+20,000.00     " for the result 

print(f"a:+,.2f") # >> +20,000.00
print(f"{a:<20+,.2f}") # >> ValueError: Invalid format specifier

print(f"{a:<20,.2f}") # >> '20,000.00           '
print(f"{a:+<20,.2f}") # >> '20,000.00+++++++++++' # Not what I want

其他任何东西都会给ValueError: Invalid format specifier我。

为什么不能将<20参数与+参数一起使用?

实际上,我发现这种嵌套形式有效,但不是最理想的。还有其他方法吗?

print(f"{f'{a:+,.2f}':<20}") # >> '+20,000.00          ' # It works but nested form sucks. 
4

1 回答 1

0

Asksed the same question on r/learnpython and got the answer.


efmccurdy

15 minutes ago

The sign goes before the width:

https://python-reference.readthedocs.io/en/latest/docs/functions/format.html

>>> f"{a:<+20,.2f}"
'+20,000.00          '
>>>
于 2021-05-07T14:33:08.400 回答