Search code examples
pythonf-string

How do I format both a string and variable in an f-string?


I'm trying to move both the "$" and totalTransactionCost to the right side of the field.

My current code is : print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")

The code is able to move the totalTransactionCost to the right side of the field, but how can I include the "$" too?


Solution

  • You can use nested f-strings, which basically divides formatting into two steps: first, format the number as a comma-separated two-decimal string, and attach the $, and then fill the whole string with leading spaces.

    >>> totalTransactionCost = 10000
    >>> print(f"Total Cost Of All Transactions: {f'${totalTransactionCost:,.2f}':>64}")
    Total Cost Of All Transactions:                                                       $10,000.00