0

I read format string mini-language from Python doc and tried to do this:

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

Anything else will give ValueError: Invalid format specifier to me.

Why is it not possible to use <20 argument with + argument?

Actually I found this nested form works but it is suboptimal. Is there any other way?

print(f"{f'{a:+,.2f}':<20}") # >> '+20,000.00          ' # It works but nested form sucks. 
user8491363
  • 2,924
  • 5
  • 19
  • 28

1 Answers1

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          '
>>>
user8491363
  • 2,924
  • 5
  • 19
  • 28