3

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

An explanation would enrich the answer
1

f-string offers flexibility.
If the currency is determined by the system, locale allows leveraging the system's setting: LC_MONETARY for currency

Below is a f-string walkthrough

## input value or use default
totalTransactionCost = input('enter amount e.g 50000') or '50000'

## OP's code:
#print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")

## f-string with formatting
## :,.2f  || use thousand separator with 2 decimal places
## :>63 || > aligns right with 63 spaces
## :<      || < aligns left
## { ... :,.2f} apply to inner f-string value
## {f'${ ... }':>64}  || apply to outer f-string value

print(f'|Total Cost of All Transactions|: {f"${int(totalTransactionCost):,.2f}":>64}')

## Note that the inner and outer uses different escapes. 
## The order doesn't matter though. Here, inner is " and outer is '.

|enter amount e.g 50000| 750000
Total Cost of All Transactions:                                                      $750,000.00

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.