What does this string format mean: (return f"${value:,.2f}")

1.1k Views Asked by At

I'm working on cs50's web track Finance Project, and in their helpers.py file they have the following function:

def usd(value):
    """Format value as USD."""
    return f"${value:,.2f}"

I believe that it takes a value and transforms into USD format. But in my html (using flask), I'm supposed to use it like this:

{{ quote["price"] | usd }}

Also, what does the | do to quote["price"]. Hopefully you can help me, thanks! :)

1

There are 1 best solutions below

0
On BEST ANSWER

Flask uses Jinja templates to generate the HTML.

Things in between {{ and }} are expressions in Jinja and get evaluated. You can take a value and apply a filter to it via the | method.

So {{ quote["price"] | usd }} means display the value of quote["price"] after applying the custom usd filter on the expression.

Your explanation of the usd filter function is accurate, it takes a number and makes sure it's display with as 2 decimal floating point.

You can read more about Jinja expressions/variables and filters here.